The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(bot-mode): run same-gateway Group Chats without Desktop
David Dudok de Wit93c7089f709f
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.pynew file mode 100644index 00000000000..dc4c26fde1a--- /dev/null+++ b/gateway/hosted_room_discussion.py@@ -0,0 +1,1320 @@+"""Deterministic policy for same-gateway hosted-room Discussions.++This module translates a frozen local member roster and the complete typed room+log into one next driver task. It performs no I/O, starts no workers, and knows+nothing about transports or model runtimes. Callers persist the returned task+with :mod:`gateway.hosted_room_driver` and append publication plans with+:mod:`gateway.hosted_rooms`.++The unpublished driver payload intentionally remains unchanged. Discussion+coordinates live in deterministic ``TaskIdentity`` values and typed terminal+events; a restart can therefore reconstruct a task without widening the driver+schema. Callers must reconcile terminal driver rows into publication plans+before asking for the next task.+"""++from __future__ import annotations++import hashlib+import json+import re+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from typing import Any, Literal++from gateway import hosted_room_driver as driver+from gateway import hosted_rooms+++MAX_DISCUSSION_MEMBERS = 6+MIN_DISCUSSION_MEMBERS = 2+MAX_DISCUSSION_ROUNDS = 3+MAX_DISCUSSION_MESSAGES = 10+MAX_DISCUSSION_DELTA_LINES = 24+MAX_USER_TEXT_BYTES = 64 * 1024+MAX_MEMBER_TEXT_BYTES = 64 * 1024+_TRUNCATED_REPLY_NOTICE = (+ "\n\n[Reply truncated. Ask the Bot to share the full result as a file.]"+)++DecisionStatus = Literal["idle", "task", "settled", "bounded"]+TerminalKind = Literal["settled", "failed", "cancelled", "deferred"]++_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")+_MENTION_RE = re.compile(r"@([A-Za-z0-9][A-Za-z0-9._:-]*)", re.IGNORECASE)+_TURN_ID_RE = re.compile(+ r"^d(?P<source>[1-9][0-9]*)\.r(?P<round>[0-2])\."+ r"p(?P<position>[0-5])\.s(?P<seen>[1-9][0-9]*)\."+ r"m(?P<member>[0-9a-f]{24})$"+)++_MEMBER_FIELDS = frozenset({"member_id", "profile", "handle", "display_name"})+_REMOTE_MEMBER_FIELDS = frozenset({+ "connectionId",+ "connectionKind",+ "connectionLabel",+ "connection_id",+ "connection_kind",+ "connection_label",+ "remoteSource",+ "route",+ "sourceMissing",+ "sourceReachable",+ "sourceScoped",+ "targetProfile",+ "target_profile",+})+_USER_PAYLOAD_FIELDS = frozenset({"text", "thread_id"})+_MEMBER_MESSAGE_FIELDS = frozenset({+ "discussion_event_id",+ "member_id",+ "member_index",+ "round_index",+ "task_id",+ "text",+ "thread_id",+ "turn_id",+})+_TERMINAL_COMMON_FIELDS = frozenset({+ "discussion_event_id",+ "member_id",+ "member_index",+ "round_index",+ "seen_through_seq",+ "task_id",+ "thread_id",+ "turn_id",+})+_TERMINAL_EXTRA_FIELDS = {+ "turn.settled": frozenset({"message_event_id", "passed"}),+ "turn.failed": frozenset({"error"}),+ "turn.cancelled": frozenset({"reason"}),+ "turn.deferred": frozenset({"execution_generation", "reason"}),+}+_TERMINAL_EVENT_KINDS = frozenset(_TERMINAL_EXTRA_FIELDS)+_ROOM_ACTIVITY_FIELDS = frozenset({+ "status",+ "reason_code",+ "thread_id",+ "discussion_event_id",+})+_ROOM_STOP_FIELDS = frozenset({"cancel_id"})+++class DiscussionPolicyError(ValueError):+ """Base class for invalid policy input or unreconstructable state."""+++class DiscussionValidationError(DiscussionPolicyError):+ """Raised when a room, roster, payload, or typed event is malformed."""+++class DiscussionReconstructionError(DiscussionPolicyError):+ """Raised when a persisted task cannot be reproduced from durable state."""+++@dataclass(frozen=True)+class DiscussionMember:+ """One immutable member local to the room's authority gateway."""++ member_id: str+ profile: str+ handle: str+ display_name: str = ""+++@dataclass(frozen=True)+class DiscussionRoom:+ """Validated policy projection of one active hosted room."""++ room_id: str+ name: str+ members: tuple[DiscussionMember, ...]+ gateway_id: str+ authority_epoch: int+++@dataclass(frozen=True)+class DiscussionTaskPlan:+ """One deterministic member turn compatible with the driver schema."""++ identity: driver.TaskIdentity+ payload: Mapping[str, Any]+ discussion_event_id: str+ member: DiscussionMember+ member_index: int+ round_index: int+ seen_through_seq: int+++@dataclass(frozen=True)+class DiscussionDecision:+ """Current result of replaying one room's Discussion policy."""++ status: DecisionStatus+ reason: str+ discussion_event_id: str | None = None+ source_event_seq: int | None = None+ thread_id: str | None = None+ task: DiscussionTaskPlan | None = None+++@dataclass(frozen=True)+class EventPlan:+ """One idempotent append for :func:`gateway.hosted_rooms.append_event`."""++ event_id: str+ kind: str+ actor: Mapping[str, str]+ payload: Mapping[str, Any]+ authority_gateway_id: str+ authority_epoch: int++ def append_kwargs(self, room_id: str) -> dict[str, Any]:+ """Return keyword arguments accepted by ``append_event``."""++ return {+ "room_id": room_id,+ "event_id": self.event_id,+ "kind": self.kind,+ "actor": dict(self.actor),+ "payload": dict(self.payload),+ "authority_gateway_id": self.authority_gateway_id,+ "authority_epoch": self.authority_epoch,+ }+++@dataclass(frozen=True)+class PublicationPlan:+ """Ordered visible and terminal effects for one driver task."""++ task_id: str+ terminal_kind: str+ events: tuple[EventPlan, ...]+++@dataclass(frozen=True)+class _ValidatedEvent:+ raw: Mapping[str, Any]+ seq: int+ event_id: str+ kind: str+ actor: Mapping[str, Any]+ payload: Mapping[str, Any]+++def _identifier(value: Any, *, label: str) -> str:+ if not isinstance(value, str):+ raise DiscussionValidationError(f"{label} must be a string")+ normalized = value.strip()+ if (+ not normalized+ or len(normalized) > driver.MAX_IDENTIFIER_CHARS+ or not _IDENTIFIER_RE.fullmatch(normalized)+ ):+ raise DiscussionValidationError(f"invalid {label}")+ return normalized+++def _positive_int(value: Any, *, label: str, maximum: int | None = None) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise DiscussionValidationError(f"{label} must be a positive integer")+ if maximum is not None and value > maximum:+ raise DiscussionValidationError(f"{label} must be at most {maximum}")+ return value+++def _zero_based_int(value: Any, *, label: str, maximum: int) -> int:+ if (+ isinstance(value, bool)+ or not isinstance(value, int)+ or not 0 <= value <= maximum+ ):+ raise DiscussionValidationError(+ f"{label} must be an integer between 0 and {maximum}"+ )+ return value+++def _exact_fields(+ value: Any,+ *,+ label: str,+ required: frozenset[str],+ optional: frozenset[str] = frozenset(),+) -> Mapping[str, Any]:+ if not isinstance(value, Mapping):+ raise DiscussionValidationError(f"{label} must be an object")+ keys = frozenset(value)+ missing = required - keys+ unknown = keys - required - optional+ if missing:+ raise DiscussionValidationError(+ f"{label} is missing fields: {', '.join(sorted(missing))}"+ )+ if unknown:+ raise DiscussionValidationError(+ f"{label} has unknown fields: {', '.join(sorted(unknown))}"+ )+ return value+++def validate_user_payload(value: Any) -> dict[str, Any]:+ """Validate and normalize the exact ``message.user`` Discussion payload."""++ payload = _exact_fields(+ value,+ label="user payload",+ required=_USER_PAYLOAD_FIELDS,+ )+ text = payload["text"]+ if not isinstance(text, str):+ raise DiscussionValidationError("user payload text must be a string")+ text = text.strip()+ if not text:+ raise DiscussionValidationError("user payload text must not be empty")+ if len(text.encode("utf-8")) > MAX_USER_TEXT_BYTES:+ raise DiscussionValidationError("user payload text is too large")+ thread_id = _identifier(payload["thread_id"], label="thread_id")+ return {"text": text, "thread_id": thread_id}+++def validate_roster(+ value: Any,+ *,+ local_profiles: Iterable[str],+) -> tuple[DiscussionMember, ...]:+ """Validate a frozen 2-6 member roster of profiles on this gateway."""++ if not isinstance(value, list):+ raise DiscussionValidationError("members must be a list")+ if not MIN_DISCUSSION_MEMBERS <= len(value) <= MAX_DISCUSSION_MEMBERS:+ raise DiscussionValidationError(+ f"members must contain between {MIN_DISCUSSION_MEMBERS} and "+ f"{MAX_DISCUSSION_MEMBERS} entries"+ )++ known_profiles = {+ _identifier(profile, label="local profile") for profile in local_profiles+ }+ members: list[DiscussionMember] = []+ profiles: set[str] = set()+ handles: set[str] = set()+ member_ids: set[str] = set()++ for index, raw in enumerate(value):+ if not isinstance(raw, Mapping):+ raise DiscussionValidationError(f"member {index} must be an object")+ remote_fields = frozenset(raw) & _REMOTE_MEMBER_FIELDS+ if remote_fields:+ raise DiscussionValidationError(+ f"member {index} contains cross-gateway fields: "+ f"{', '.join(sorted(remote_fields))}"+ )+ member = _exact_fields(+ raw,+ label=f"member {index}",+ required=frozenset({"member_id", "profile", "handle"}),+ optional=frozenset({"display_name"}),+ )+ member_id = _identifier(member["member_id"], label=f"member {index} id")+ profile = _identifier(member["profile"], label=f"member {index} profile")+ handle = _identifier(member["handle"], label=f"member {index} handle")+ if profile not in known_profiles:+ raise DiscussionValidationError(+ f"member {index} profile '{profile}' is not local to this gateway"+ )+ display_name = member.get("display_name", "")+ if not isinstance(display_name, str):+ raise DiscussionValidationError(+ f"member {index} display_name must be a string"+ )+ display_name = display_name.strip()+ if len(display_name) > hosted_rooms.MAX_ACTOR_LABEL_CHARS:+ raise DiscussionValidationError(f"member {index} display_name is too long")++ profile_key = profile.casefold()+ handle_key = handle.casefold()+ member_key = member_id.casefold()+ if profile_key in profiles:+ raise DiscussionValidationError("member profiles must be unique")+ if handle_key in handles or handle_key in {"all", "everyone"}:+ raise DiscussionValidationError(+ "member handles must be unique and cannot reserve @all or @everyone"+ )+ if member_key in member_ids:+ raise DiscussionValidationError("member ids must be unique")+ profiles.add(profile_key)+ handles.add(handle_key)+ member_ids.add(member_key)+ members.append(+ DiscussionMember(+ member_id=member_id,+ profile=profile,+ handle=handle,+ display_name=display_name,+ )+ )+ return tuple(members)+++def validate_room(+ value: Any,+ *,+ local_profiles: Iterable[str],+) -> DiscussionRoom:+ """Project a hosted-room row into the strict same-gateway policy shape."""++ if not isinstance(value, Mapping):+ raise DiscussionValidationError("room must be an object")+ if value.get("disbanded_at") is not None:+ raise DiscussionValidationError("room is disbanded")+ room_id = _identifier(value.get("room_id"), label="room_id")+ name = value.get("name")+ if not isinstance(name, str) or not name.strip():+ raise DiscussionValidationError("room name must be a non-empty string")+ name = name.strip()+ if len(name) > hosted_rooms.MAX_ROOM_NAME_CHARS:+ raise DiscussionValidationError("room name is too long")+ gateway_id = _identifier(+ value.get("authority_gateway_id"),+ label="authority_gateway_id",+ )+ authority_epoch = _positive_int(+ value.get("authority_epoch"),+ label="authority_epoch",+ )+ members = validate_roster(value.get("members"), local_profiles=local_profiles)+ return DiscussionRoom(+ room_id=room_id,+ name=name,+ members=members,+ gateway_id=gateway_id,+ authority_epoch=authority_epoch,+ )+++def is_pass_text(value: Any) -> bool:+ """Return whether a settled member result is Discussion silence."""++ text = str(value or "").strip()+ return (+ not text+ or re.fullmatch(r"\(?\s*pass\s*\)?\.?", text, re.IGNORECASE) is not None+ )+++def resolve_mentions(+ texts: Iterable[str],+ members: Sequence[DiscussionMember],+ *,+ default_all: bool = True,+) -> tuple[DiscussionMember, ...]:+ """Resolve member handles deterministically against the frozen roster."""++ by_handle = {member.handle.casefold(): member for member in members}+ mentioned: set[str] = set()+ everyone = False+ for text in texts:+ for match in _MENTION_RE.finditer(str(text or "")):+ handle = match.group(1).casefold()+ if handle in {"all", "everyone"}:+ everyone = True+ elif handle in by_handle:+ mentioned.add(handle)+ if everyone or (default_all and not mentioned):+ return tuple(members)+ return tuple(member for member in members if member.handle.casefold() in mentioned)+++def _unaddressed_member_mentions(+ messages: Sequence[_ValidatedEvent],+ room: DiscussionRoom,+) -> tuple[DiscussionMember, ...]:+ """Return peers explicitly cited by a Bot and not heard from afterward."""++ cited_at: dict[str, int] = {}+ last_post_at: dict[str, int] = {}+ for event in messages:+ if event.kind != "message.member":+ continue+ speaker_id = str(event.payload["member_id"])+ last_post_at[speaker_id] = event.seq+ cited = resolve_mentions(+ (str(event.payload["text"]),),+ room.members,+ default_all=False,+ )+ for member in cited:+ if member.member_id != speaker_id:+ cited_at[member.member_id] = event.seq+ return tuple(+ member+ for member in room.members+ if member.member_id in cited_at+ and last_post_at.get(member.member_id, 0) <= cited_at[member.member_id]+ )+++def _validate_event(+ raw: Any,+ *,+ room: DiscussionRoom,+ previous_seq: int,+) -> _ValidatedEvent:+ if not isinstance(raw, Mapping):+ raise DiscussionValidationError("room event must be an object")+ if raw.get("room_id") != room.room_id:+ raise DiscussionValidationError("room event belongs to a different room")+ seq = _positive_int(raw.get("seq"), label="event seq")+ if seq <= previous_seq:+ raise DiscussionValidationError("room events must be in strict sequence order")+ event_id = _identifier(raw.get("event_id"), label="event_id")+ kind = raw.get("kind")+ if not isinstance(kind, str):+ raise DiscussionValidationError("event kind must be a string")+ actor = raw.get("actor")+ if not isinstance(actor, Mapping):+ raise DiscussionValidationError("event actor must be an object")+ payload = raw.get("payload")+ if not isinstance(payload, Mapping):+ raise DiscussionValidationError("event payload must be an object")++ if kind == "message.user":+ payload = validate_user_payload(payload)+ if actor.get("kind") != "user":+ raise DiscussionValidationError("message.user requires a user actor")+ elif kind == "message.member":+ if raw.get("authority_epoch") != room.authority_epoch:+ raise DiscussionValidationError(+ "message.member authority epoch does not match the room"+ )+ _validate_member_message(payload, actor=actor, room=room)+ elif kind in _TERMINAL_EVENT_KINDS:+ if raw.get("authority_epoch") != room.authority_epoch:+ raise DiscussionValidationError(+ f"{kind} authority epoch does not match the room"+ )+ _validate_terminal_event(kind, payload, actor=actor, room=room)+ elif kind == "room.activity":+ if raw.get("authority_epoch") != room.authority_epoch:+ raise DiscussionValidationError(+ "room.activity authority epoch does not match the room"+ )+ _exact_fields(+ payload,+ label="room.activity payload",+ required=_ROOM_ACTIVITY_FIELDS,+ )+ if payload.get("status") not in {"settled", "bounded"}:+ raise DiscussionValidationError("invalid room.activity status")+ _identifier(payload.get("reason_code"), label="reason_code")+ _identifier(payload.get("thread_id"), label="thread_id")+ _identifier(payload.get("discussion_event_id"), label="discussion_event_id")+ if actor.get("kind") != "gateway" or actor.get("id") != room.gateway_id:+ raise DiscussionValidationError("room.activity requires the room gateway")+ elif kind == "room.stop_requested":+ if raw.get("authority_epoch") != room.authority_epoch:+ raise DiscussionValidationError(+ "room.stop_requested authority epoch does not match the room"+ )+ _exact_fields(+ payload,+ label="room.stop_requested payload",+ required=_ROOM_STOP_FIELDS,+ )+ _identifier(payload.get("cancel_id"), label="cancel_id")+ if actor.get("kind") != "gateway" or actor.get("id") != room.gateway_id:+ raise DiscussionValidationError(+ "room.stop_requested requires the room gateway"+ )++ return _ValidatedEvent(+ raw=raw,+ seq=seq,+ event_id=event_id,+ kind=kind,+ actor=actor,+ payload=payload,+ )+++def _member_by_id(room: DiscussionRoom, member_id: Any) -> DiscussionMember:+ normalized = _identifier(member_id, label="member_id")+ for member in room.members:+ if member.member_id == normalized:+ return member+ raise DiscussionValidationError(f"unknown Discussion member '{normalized}'")+++def _validate_turn_coordinates(+ payload: Mapping[str, Any], room: DiscussionRoom+) -> None:+ _member_by_id(room, payload.get("member_id"))+ member_index = _zero_based_int(+ payload.get("member_index"),+ label="member_index",+ maximum=MAX_DISCUSSION_MEMBERS - 1,+ )+ round_index = _zero_based_int(+ payload.get("round_index"),+ label="round_index",+ maximum=MAX_DISCUSSION_ROUNDS - 1,+ )+ thread_id = _identifier(payload.get("thread_id"), label="thread_id")+ task_id = _identifier(payload.get("task_id"), label="task_id")+ turn_id = _identifier(payload.get("turn_id"), label="turn_id")+ discussion_event_id = _identifier(+ payload.get("discussion_event_id"),+ label="discussion_event_id",+ )+ del member_index, round_index, thread_id, task_id, turn_id, discussion_event_id+++def _validate_member_message(+ payload: Mapping[str, Any],+ *,+ actor: Mapping[str, Any],+ room: DiscussionRoom,+) -> None:+ _exact_fields(+ payload,+ label="message.member payload",+ required=_MEMBER_MESSAGE_FIELDS,+ )+ _validate_turn_coordinates(payload, room)+ text = payload.get("text")+ if not isinstance(text, str) or not text.strip() or is_pass_text(text):+ raise DiscussionValidationError("message.member text must be a non-pass string")+ member = _member_by_id(room, payload.get("member_id"))+ if (+ actor.get("kind") != "member"+ or actor.get("id") != member.member_id+ or actor.get("profile") != member.profile+ or actor.get("connection_id") is not None+ ):+ raise DiscussionValidationError("message.member actor does not match roster")+++def _validate_terminal_event(+ kind: str,+ payload: Mapping[str, Any],+ *,+ actor: Mapping[str, Any],+ room: DiscussionRoom,+) -> None:+ required = _TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind]+ _exact_fields(payload, label=f"{kind} payload", required=required)+ _validate_turn_coordinates(payload, room)+ _positive_int(payload.get("seen_through_seq"), label="seen_through_seq")+ if (+ actor.get("kind") != "gateway"+ or actor.get("id") != room.gateway_id+ or actor.get("connection_id") is not None+ ):+ raise DiscussionValidationError(f"{kind} requires a gateway actor")+ if kind == "turn.settled":+ if not isinstance(payload.get("passed"), bool):+ raise DiscussionValidationError("turn.settled passed must be a boolean")+ message_event_id = payload.get("message_event_id")+ if payload["passed"]:+ if message_event_id is not None:+ raise DiscussionValidationError(+ "a passed turn cannot reference a member message"+ )+ else:+ _identifier(message_event_id, label="message_event_id")+ else:+ field = "error" if kind == "turn.failed" else "reason"+ if not isinstance(payload.get(field), str) or not payload[field].strip():+ raise DiscussionValidationError(f"{kind} {field} must be non-empty")+ if kind == "turn.deferred":+ _positive_int(+ payload.get("execution_generation"),+ label="execution_generation",+ )+++def _validated_events(+ events: Sequence[Mapping[str, Any]],+ *,+ room: DiscussionRoom,+) -> tuple[_ValidatedEvent, ...]:+ validated: list[_ValidatedEvent] = []+ previous_seq = 0+ event_ids: set[str] = set()+ for raw in events:+ event = _validate_event(raw, room=room, previous_seq=previous_seq)+ if event.event_id in event_ids:+ raise DiscussionValidationError("room event ids must be unique")+ validated.append(event)+ previous_seq = event.seq+ event_ids.add(event.event_id)+ return tuple(validated)+++def _discussion_user_events(+ events: Sequence[_ValidatedEvent],+) -> tuple[_ValidatedEvent, ...]:+ return tuple(event for event in events if event.kind == "message.user")+++def _message_events(+ events: Sequence[_ValidatedEvent],+ *,+ thread_id: str | None = None,+ maximum_seq: int | None = None,+) -> tuple[_ValidatedEvent, ...]:+ result = []+ for event in events:+ if event.kind not in {"message.user", "message.member"}:+ continue+ if thread_id is not None and event.payload.get("thread_id") != thread_id:+ continue+ if maximum_seq is not None and event.seq > maximum_seq:+ continue+ result.append(event)+ return tuple(result)+++def derive_member_watermarks(+ room_value: Any,+ events: Sequence[Mapping[str, Any]],+ *,+ local_profiles: Iterable[str],+) -> dict[tuple[str, str], int]:+ """Derive ``(thread_id, member_id)`` watermarks from terminal events."""++ room = validate_room(room_value, local_profiles=local_profiles)+ validated = _validated_events(events, room=room)+ return _derive_member_watermarks(validated)+++def _derive_member_watermarks(+ events: Sequence[_ValidatedEvent],+) -> dict[tuple[str, str], int]:+ messages_by_id = {+ event.event_id: event for event in events if event.kind == "message.member"+ }+ terminal_by_task: dict[str, _ValidatedEvent] = {}+ watermarks: dict[tuple[str, str], int] = {}+ for event in events:+ if event.kind not in _TERMINAL_EVENT_KINDS:+ continue+ task_id = str(event.payload["task_id"])+ previous = terminal_by_task.get(task_id)+ if previous is not None:+ if previous.kind != "turn.deferred":+ raise DiscussionValidationError(+ f"task '{task_id}' has more than one terminal room event"+ )+ if event.kind == "turn.deferred" and int(+ event.payload["execution_generation"]+ ) <= int(previous.payload["execution_generation"]):+ raise DiscussionValidationError(+ f"task '{task_id}' deferral generation did not advance"+ )+ terminal_by_task[task_id] = event+ key = (str(event.payload["thread_id"]), str(event.payload["member_id"]))+ watermark = int(event.payload["seen_through_seq"])+ if event.kind == "turn.settled" and not event.payload["passed"]:+ message_id = str(event.payload["message_event_id"])+ message = messages_by_id.get(message_id)+ if (+ message is None+ or message.payload.get("task_id") != task_id+ or message.payload.get("member_id") != event.payload.get("member_id")+ or message.payload.get("thread_id") != event.payload.get("thread_id")+ ):+ raise DiscussionValidationError(+ "turn.settled references no matching member message"+ )+ watermark = max(watermark, message.seq)+ watermarks[key] = max(watermarks.get(key, 0), watermark)+ return watermarks+++def _member_digest(member: DiscussionMember) -> str:+ seed = f"{member.member_id}\0{member.profile}\0{member.handle}"+ return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:24]+++def _rotate(+ members: Sequence[DiscussionMember], round_index: int+) -> tuple[DiscussionMember, ...]:+ if len(members) < 2:+ return tuple(members)+ shift = round_index % len(members)+ return tuple((*members[shift:], *members[:shift]))+++def _format_message(event: _ValidatedEvent, room: DiscussionRoom) -> str:+ text = str(event.payload["text"])+ if event.kind == "message.user":+ return f"User (user): {text}"+ member = _member_by_id(room, event.payload["member_id"])+ return f"@{member.handle}: {text}"+++def _truncate_utf8_text(value: Any, *, max_bytes: int, suffix: str = "") -> str:+ text = str(value or "")+ encoded = text.encode("utf-8")+ if len(encoded) <= max_bytes:+ return text+ suffix_bytes = suffix.encode("utf-8")+ prefix = encoded[: max(0, max_bytes - len(suffix_bytes))]+ while prefix:+ try:+ return prefix.decode("utf-8") + suffix+ except UnicodeDecodeError:+ prefix = prefix[:-1]+ return suffix.strip()+++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:+ ]+ peers = ", ".join(+ f"@{candidate.handle}"+ for candidate in room.members+ if candidate.member_id != member.member_id+ )+ opening = [+ f'[Discussion: "{room.name}"] You are @{member.handle}, one participant '+ f"with {peers or 'no other members'} and the user.",+ "",+ "New messages in this thread since your last turn (oldest first):",+ ]+ rules = [+ "",+ "Rules for this Discussion:",+ "- Reply with one conversational message only when you have something new worth adding.",+ '- If you have nothing new to add, reply with exactly "(pass)".',+ "- Mention a teammate by handle to pull them into the next round; do not repeat points already made.",+ "- Never reveal content from private conversations. Your reply is published verbatim.",+ ]+ fixed_bytes = len("\n".join([*opening, *rules]).encode("utf-8"))+ available = max(0, driver.MAX_PROMPT_BYTES - fixed_bytes - 1)+ selected: list[str] = []+ omitted = False+ for event in reversed(delta):+ line = f" {_format_message(event, room)}"+ line_bytes = len(line.encode("utf-8")) + 1+ if line_bytes <= available:+ selected.append(line)+ available -= line_bytes+ continue+ if not selected and available > 32:+ selected.append(_truncate_utf8_text(line, max_bytes=available))+ omitted = True+ break+ selected.reverse()+ if omitted:+ selected.insert(0, " [Earlier content omitted to fit this turn.]")+ prompt = "\n".join([*opening, *selected, *rules])+ if len(prompt.encode("utf-8")) > driver.MAX_PROMPT_BYTES:+ raise DiscussionValidationError("Discussion prompt exceeds the driver limit")+ return prompt+++def _turn_id(+ *,+ source_event_seq: int,+ round_index: int,+ member_index: int,+ seen_through_seq: int,+ member: DiscussionMember,+) -> str:+ return (+ f"d{source_event_seq}.r{round_index}.p{member_index}."+ f"s{seen_through_seq}.m{_member_digest(member)}"+ )+++def _task_id(+ *,+ room: DiscussionRoom,+ discussion_event: _ValidatedEvent,+ member: DiscussionMember,+ member_index: int,+ round_index: int,+ seen_through_seq: int,+ prompt: str,+) -> str:+ seed = json.dumps(+ {+ "discussion_event_id": discussion_event.event_id,+ "member_id": member.member_id,+ "member_index": member_index,+ "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),+ "room_id": room.room_id,+ "round_index": round_index,+ "seen_through_seq": seen_through_seq,+ "source_event_seq": discussion_event.seq,+ "thread_id": discussion_event.payload["thread_id"],+ },+ ensure_ascii=True,+ sort_keys=True,+ separators=(",", ":"),+ )+ return f"dtask:{hashlib.sha256(seed.encode('utf-8')).hexdigest()[:48]}"+++def _make_task_plan(+ *,+ room: DiscussionRoom,+ discussion_event: _ValidatedEvent,+ member: DiscussionMember,+ member_index: int,+ round_index: int,+ seen_through_seq: int,+ prompt: str,+) -> DiscussionTaskPlan:+ turn_id = _turn_id(+ source_event_seq=discussion_event.seq,+ round_index=round_index,+ member_index=member_index,+ seen_through_seq=seen_through_seq,+ member=member,+ )+ task_id = _task_id(+ room=room,+ discussion_event=discussion_event,+ member=member,+ member_index=member_index,+ round_index=round_index,+ seen_through_seq=seen_through_seq,+ prompt=prompt,+ )+ identity = driver.TaskIdentity(+ room_id=room.room_id,+ task_id=task_id,+ thread_id=str(discussion_event.payload["thread_id"]),+ turn_id=turn_id,+ )+ payload = {+ "target_profile": member.profile,+ "prompt": prompt,+ "source_event_seq": discussion_event.seq,+ }+ return DiscussionTaskPlan(+ identity=identity,+ payload=payload,+ discussion_event_id=discussion_event.event_id,+ member=member,+ member_index=member_index,+ round_index=round_index,+ seen_through_seq=seen_through_seq,+ )+++def plan_next_task(+ room_value: Any,+ events: Sequence[Mapping[str, Any]],+ *,+ local_profiles: Iterable[str],+ initial_watermarks: Mapping[tuple[str, str], int] | None = None,+) -> DiscussionDecision:+ """Replay the complete room log and return at most one next member task."""++ room = validate_room(room_value, local_profiles=local_profiles)+ validated = _validated_events(events, room=room)+ user_events = _discussion_user_events(validated)+ 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+ if event.kind == "room.activity"+ and event.payload.get("status") in {"settled", "bounded"}+ }+ latest_by_thread: dict[str, _ValidatedEvent] = {}+ for event in user_events:+ latest_by_thread[str(event.payload["thread_id"])] = event+ pending_user_events = tuple(+ event+ for event in sorted(latest_by_thread.values(), key=lambda item: item.seq)+ if event.seq > stopped_through_seq+ and event.event_id not in completed_discussion_ids+ )+ if not pending_user_events:+ return DiscussionDecision(status="idle", reason="no_pending_user_event")++ discussion = pending_user_events[0]+ thread_id = str(discussion.payload["thread_id"])+ committed_member_message_ids = {+ str(event.payload["message_event_id"])+ for event in validated+ if event.kind == "turn.settled"+ and event.payload.get("message_event_id") is not None+ }+ # Publication writes the visible member message before the terminal event.+ # A crash in that gap leaves the message in the log, but it is not committed+ # policy input yet: ignoring it reproduces the original task coordinates so+ # the caller can inspect the terminal driver row and finish publication.+ thread_messages = tuple(+ event+ for event in _message_events(validated, thread_id=thread_id)+ if event.kind == "message.user"+ or event.event_id in committed_member_message_ids+ )+ discussion_messages = tuple(+ event for event in thread_messages if event.seq >= discussion.seq+ )+ member_messages = tuple(+ event+ for event in thread_messages+ if event.kind == "message.member"+ and event.payload.get("discussion_event_id") == discussion.event_id+ )+ if len(member_messages) >= MAX_DISCUSSION_MESSAGES:+ return DiscussionDecision(+ status="bounded",+ reason="max_messages",+ discussion_event_id=discussion.event_id,+ source_event_seq=discussion.seq,+ thread_id=thread_id,+ )++ terminals = {+ (int(event.payload["round_index"]), str(event.payload["member_id"])): event+ for event in validated+ if event.kind in _TERMINAL_EVENT_KINDS+ and event.payload.get("discussion_event_id") == discussion.event_id+ }+ watermarks = {+ (str(thread_id), str(member_id)): int(value)+ for (thread_id, member_id), value in (initial_watermarks or {}).items()+ if int(value) >= 0+ }+ for key, value in _derive_member_watermarks(validated).items():+ watermarks[key] = max(watermarks.get(key, 0), value)+ seen_through_seq = max(event.seq for event in thread_messages)++ for round_index in range(MAX_DISCUSSION_ROUNDS):+ # The user's message selects the first round, with no mention meaning+ # everyone. Later rounds are opt-in: only a peer explicitly cited by a+ # Bot and not heard from afterward gets another turn. Every member's+ # watermark remains intact, so a peer cited later still receives the+ # complete bounded transcript delta without consuming turns meanwhile.+ responders = (+ resolve_mentions((str(discussion.payload["text"]),), room.members)+ if round_index == 0+ else _unaddressed_member_mentions(discussion_messages, room)+ )+ ordered = _rotate(responders, round_index)+ for member_index, member in enumerate(ordered):+ if (round_index, member.member_id) in terminals:+ continue+ watermark = watermarks.get((thread_id, member.member_id), 0)+ delta = [+ event+ for event in thread_messages+ if watermark < event.seq <= seen_through_seq+ ]+ if not delta:+ continue+ prompt = _build_prompt(+ room=room,+ member=member,+ messages=thread_messages,+ watermark=watermark,+ seen_through_seq=seen_through_seq,+ )+ task = _make_task_plan(+ room=room,+ discussion_event=discussion,+ member=member,+ member_index=member_index,+ round_index=round_index,+ seen_through_seq=seen_through_seq,+ prompt=prompt,+ )+ return DiscussionDecision(+ status="task",+ reason="member_turn",+ discussion_event_id=discussion.event_id,+ source_event_seq=discussion.seq,+ thread_id=thread_id,+ task=task,+ )++ spoke = any(+ int(event.payload["round_index"]) == round_index+ for event in member_messages+ )+ if not spoke:+ return DiscussionDecision(+ status="settled",+ reason="silent_round",+ discussion_event_id=discussion.event_id,+ source_event_seq=discussion.seq,+ thread_id=thread_id,+ )+ if round_index == MAX_DISCUSSION_ROUNDS - 1:+ return DiscussionDecision(+ status="bounded",+ reason="max_rounds",+ discussion_event_id=discussion.event_id,+ source_event_seq=discussion.seq,+ thread_id=thread_id,+ )++ raise AssertionError("bounded Discussion loop exhausted unexpectedly")+++def reconstruct_task_plan(+ room_value: Any,+ events: Sequence[Mapping[str, Any]],+ task: Mapping[str, Any],+ *,+ local_profiles: Iterable[str],+) -> DiscussionTaskPlan:+ """Reconstruct and verify one persisted driver task after a restart."""++ room = validate_room(room_value, local_profiles=local_profiles)+ validated = _validated_events(events, room=room)+ identity = task.get("identity")+ payload = task.get("payload")+ if not isinstance(identity, driver.TaskIdentity) or not isinstance(+ payload, Mapping+ ):+ raise DiscussionReconstructionError(+ "driver task has no valid identity or payload"+ )+ if frozenset(payload) != frozenset({+ "target_profile",+ "prompt",+ "source_event_seq",+ }):+ raise DiscussionReconstructionError("driver task payload shape changed")+ match = _TURN_ID_RE.fullmatch(identity.turn_id)+ if match is None:+ raise DiscussionReconstructionError("turn_id is not a Discussion coordinate")+ source_event_seq = int(match.group("source"))+ round_index = int(match.group("round"))+ member_index = int(match.group("position"))+ seen_through_seq = int(match.group("seen"))+ if payload.get("source_event_seq") != source_event_seq:+ raise DiscussionReconstructionError("task source event does not match turn_id")+ discussion = next(+ (+ event+ for event in validated+ if event.seq == source_event_seq and event.kind == "message.user"+ ),+ None,+ )+ if discussion is None:+ raise DiscussionReconstructionError("task source user event is missing")+ if (+ identity.room_id != room.room_id+ or identity.thread_id != discussion.payload["thread_id"]+ ):+ raise DiscussionReconstructionError(+ "task identity does not match its room thread"+ )+ profile = payload.get("target_profile")+ member = next(+ (candidate for candidate in room.members if candidate.profile == profile), None+ )+ if member is None or _member_digest(member) != match.group("member"):+ raise DiscussionReconstructionError("task target member does not match turn_id")+ prompt = payload.get("prompt")+ if not isinstance(prompt, str) or not prompt.strip():+ raise DiscussionReconstructionError("task prompt is missing")+ if len(prompt.encode("utf-8")) > driver.MAX_PROMPT_BYTES:+ raise DiscussionReconstructionError("task prompt exceeds the driver limit")+ reconstructed = _make_task_plan(+ room=room,+ discussion_event=discussion,+ member=member,+ member_index=member_index,+ round_index=round_index,+ seen_through_seq=seen_through_seq,+ prompt=prompt,+ )+ if reconstructed.identity != identity or dict(reconstructed.payload) != dict(+ payload+ ):+ raise DiscussionReconstructionError(+ "driver task failed deterministic reconstruction"+ )+ return reconstructed+++def _terminal_text(result: Any, *, field: str, fallback: str) -> str:+ if isinstance(result, Mapping):+ value = result.get(field)+ if value is None and field == "error":+ value = result.get("text")+ else:+ value = result+ text = str(value or "").strip()+ return text or fallback+++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:+ """Plan idempotent room effects for one terminal driver task.++ A newer user event in the same thread supersedes a late result. The task+ remains terminal in driver state, but only a deterministic cancellation is+ published, preventing stale prose and its watermark from hiding the newer+ user message.+ """++ room = validate_room(room_value, local_profiles=local_profiles)+ validated = _validated_events(events, room=room)+ if task.identity.room_id != room.room_id:+ raise DiscussionValidationError("task belongs to a different room")+ if task.member not in room.members:+ raise DiscussionValidationError("task member is not in the frozen roster")+ if status not in {"settled", "failed", "cancelled", "deferred"}:+ raise DiscussionValidationError("invalid terminal publication status")+ if status == "deferred" and (+ isinstance(execution_generation, bool)+ or not isinstance(execution_generation, int)+ or execution_generation < 1+ ):+ raise DiscussionValidationError(+ "deferred publication requires an execution generation"+ )++ newer_same_thread = any(+ event.kind == "message.user"+ and event.seq > task.seen_through_seq+ and event.payload.get("thread_id") == task.identity.thread_id+ for event in validated+ )+ effective_status: TerminalKind = (+ "cancelled" if newer_same_thread and status != "deferred" else status+ )+ digest = task.identity.task_id.removeprefix("dtask:")+ message_event_id = f"dmessage:{digest}"+ terminal_event_id = (+ f"ddeferred:{digest}:g{execution_generation}"+ if effective_status == "deferred"+ else f"dterminal:{digest}"+ )+ common = {+ "discussion_event_id": task.discussion_event_id,+ "member_id": task.member.member_id,+ "member_index": task.member_index,+ "round_index": task.round_index,+ "seen_through_seq": task.seen_through_seq,+ "task_id": task.identity.task_id,+ "thread_id": task.identity.thread_id,+ "turn_id": task.identity.turn_id,+ }+ effects: list[EventPlan] = []++ if effective_status == "settled":+ text = _truncate_utf8_text(+ _terminal_text(result, field="text", fallback=""),+ max_bytes=MAX_MEMBER_TEXT_BYTES,+ suffix=_TRUNCATED_REPLY_NOTICE,+ )+ passed = is_pass_text(text)+ if not passed:+ member_actor = {+ "kind": "member",+ "id": task.member.member_id,+ "profile": task.member.profile,+ }+ if task.member.display_name:+ member_actor["display_name"] = task.member.display_name+ effects.append(+ EventPlan(+ event_id=message_event_id,+ kind="message.member",+ actor=member_actor,+ payload={+ "discussion_event_id": task.discussion_event_id,+ "member_id": task.member.member_id,+ "member_index": task.member_index,+ "round_index": task.round_index,+ "task_id": task.identity.task_id,+ "text": text,+ "thread_id": task.identity.thread_id,+ "turn_id": task.identity.turn_id,+ },+ authority_gateway_id=room.gateway_id,+ authority_epoch=room.authority_epoch,+ )+ )+ terminal_payload = {+ **common,+ "message_event_id": None if passed else message_event_id,+ "passed": passed,+ }+ terminal_kind = "turn.settled"+ elif effective_status == "failed":+ terminal_payload = {+ **common,+ "error": _terminal_text(+ result,+ field="error",+ fallback="member turn failed",+ ),+ }+ terminal_kind = "turn.failed"+ elif effective_status == "cancelled":+ terminal_payload = {+ **common,+ "reason": (+ "superseded_by_newer_user_event"+ if newer_same_thread+ else _terminal_text(+ result,+ field="reason",+ fallback="member turn cancelled",+ )+ ),+ }+ terminal_kind = "turn.cancelled"+ else:+ terminal_payload = {+ **common,+ "execution_generation": execution_generation,+ "reason": _terminal_text(+ result,+ field="reason",+ fallback="member_unavailable",+ ),+ }+ terminal_kind = "turn.deferred"++ effects.append(+ EventPlan(+ event_id=terminal_event_id,+ kind=terminal_kind,+ actor={"kind": "gateway", "id": room.gateway_id},+ payload=terminal_payload,+ authority_gateway_id=room.gateway_id,+ authority_epoch=room.authority_epoch,+ )+ )+ return PublicationPlan(+ task_id=task.identity.task_id,+ terminal_kind=terminal_kind,+ events=tuple(effects),+ )diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pynew file mode 100644index 00000000000..55cbed15feb--- /dev/null+++ b/gateway/hosted_room_driver.py@@ -0,0 +1,1649 @@+"""Durable execution state for a same-gateway hosted room driver.++This module owns only the driver lease and task state machine. It does not+invoke models, touch sessions, or depend on the hosted-room event log. Callers+provide both the database path and clock so recovery and fencing behavior can+be tested without process-global state.+"""++from __future__ import annotations++import hashlib+import json+import math+import re+import sqlite3+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Iterator, Literal+++Clock = Callable[[], float]+TaskStatus = Literal[+ "queued",+ "running",+ "settled",+ "failed",+ "cancelled",+ "indeterminate",+ "deferred",+ "stopping",+]+TerminalStatus = Literal["settled", "failed"]++MAX_IDENTIFIER_CHARS = 128+MAX_PROMPT_BYTES = 128 * 1024+MAX_RESULT_JSON_BYTES = 256 * 1024+TERMINAL_TASK_RETENTION_SECONDS = 30 * 24 * 60 * 60+MAX_RETAINED_TERMINAL_TASKS = 2048+MAX_TASK_PRUNE_BATCH = 1000+TASK_STATUSES = frozenset({+ "queued",+ "running",+ "settled",+ "failed",+ "cancelled",+ "indeterminate",+ "deferred",+ "stopping",+})+TERMINAL_STATUSES = frozenset({"settled", "failed", "cancelled"})++_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")+_TASK_PAYLOAD_FIELDS = frozenset({"target_profile", "prompt", "source_event_seq"})+_LEASE_COLUMNS = frozenset({+ "room_id",+ "gateway_id",+ "authority_epoch",+ "process_generation",+ "lease_generation",+ "expires_at",+ "acquired_at",+ "updated_at",+ "released_at",+})+_TASK_COLUMNS = frozenset({+ "room_id",+ "task_id",+ "thread_id",+ "turn_id",+ "source_event_seq",+ "payload_json",+ "payload_digest",+ "status",+ "execution_generation",+ "cancel_generation",+ "run_gateway_id",+ "run_process_generation",+ "run_lease_generation",+ "cancel_id",+ "settlement_id",+ "settlement_status",+ "result_json",+ "created_at",+ "updated_at",+ "started_at",+ "terminal_at",+ "indeterminate_at",+})+_TASK_COLUMN_ORDER = (+ "room_id",+ "task_id",+ "thread_id",+ "turn_id",+ "source_event_seq",+ "payload_json",+ "payload_digest",+ "status",+ "execution_generation",+ "cancel_generation",+ "run_gateway_id",+ "run_process_generation",+ "run_lease_generation",+ "cancel_id",+ "settlement_id",+ "settlement_status",+ "result_json",+ "created_at",+ "updated_at",+ "started_at",+ "terminal_at",+ "indeterminate_at",+)+++class DriverStateError(ValueError):+ """Base class for invalid or conflicting driver-state operations."""+++class DriverValidationError(DriverStateError):+ """Raised when an identifier, clock, TTL, or payload is invalid."""+++class RoomUnavailableError(DriverStateError):+ """Raised when the hosted room does not exist or was disbanded."""+++class LeaseHeldError(DriverStateError):+ """Raised when another unexpired driver generation owns the room."""+++class StaleLeaseError(DriverStateError):+ """Raised when a lease generation can no longer mutate room state."""+++class TaskConflictError(DriverStateError):+ """Raised when an idempotency key is reused for different task state."""+++class StaleTaskError(DriverStateError):+ """Raised when an obsolete task attempt or cancellation tries to commit."""+++class InvalidTaskTransitionError(DriverStateError):+ """Raised when a requested task transition is not allowed."""+++def _identifier(value: Any, *, label: str) -> str:+ if not isinstance(value, str):+ raise DriverValidationError(f"{label} must be a string")+ value = value.strip()+ if (+ not value+ or len(value) > MAX_IDENTIFIER_CHARS+ or not _IDENTIFIER_RE.fullmatch(value)+ ):+ raise DriverValidationError(f"invalid {label}")+ return value+++def _timestamp(clock: Clock) -> float:+ if not callable(clock):+ raise DriverValidationError("clock must be callable")+ try:+ value = float(clock())+ except (TypeError, ValueError, OverflowError) as exc:+ raise DriverValidationError("clock must return a finite number") from exc+ if not math.isfinite(value):+ raise DriverValidationError("clock must return a finite number")+ return value+++def _ttl(value: Any) -> float:+ try:+ ttl = float(value)+ except (TypeError, ValueError, OverflowError) as exc:+ raise DriverValidationError(+ "ttl_seconds must be a finite positive number"+ ) from exc+ if not math.isfinite(ttl) or ttl <= 0:+ raise DriverValidationError("ttl_seconds must be a finite positive number")+ return ttl+++def _expiry(now: float, ttl: float) -> float:+ expires_at = now + ttl+ if not math.isfinite(expires_at):+ raise DriverValidationError("lease expiry must be finite")+ return expires_at+++def _canonical_json(value: Any) -> str:+ try:+ encoded = json.dumps(+ value,+ ensure_ascii=True,+ sort_keys=True,+ separators=(",", ":"),+ )+ except (TypeError, ValueError, RecursionError) as exc:+ raise DriverValidationError("result must be JSON-serializable") from exc+ if len(encoded.encode("utf-8")) > MAX_RESULT_JSON_BYTES:+ raise DriverValidationError("result is too large")+ return encoded+++def _authority_epoch(value: Any) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise DriverValidationError("authority_epoch must be a positive integer")+ return value+++def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:+ if not isinstance(value, dict):+ raise DriverValidationError("payload must be an object")+ unknown = set(value) - _TASK_PAYLOAD_FIELDS+ missing = _TASK_PAYLOAD_FIELDS - set(value)+ if unknown:+ raise DriverValidationError(+ f"unknown payload fields: {', '.join(sorted(unknown))}"+ )+ if missing:+ raise DriverValidationError(+ f"missing payload fields: {', '.join(sorted(missing))}"+ )++ target_profile = _identifier(value["target_profile"], label="target_profile")+ prompt = value["prompt"]+ if not isinstance(prompt, str):+ raise DriverValidationError("prompt must be a string")+ if not prompt.strip():+ raise DriverValidationError("prompt must not be empty")+ if len(prompt.encode("utf-8")) > MAX_PROMPT_BYTES:+ raise DriverValidationError("prompt is too large")+ source_event_seq = value["source_event_seq"]+ if (+ isinstance(source_event_seq, bool)+ or not isinstance(source_event_seq, int)+ or source_event_seq < 1+ ):+ raise DriverValidationError("source_event_seq must be a positive integer")++ normalized = {+ "target_profile": target_profile,+ "prompt": prompt,+ "source_event_seq": source_event_seq,+ }+ encoded = json.dumps(+ normalized,+ ensure_ascii=True,+ sort_keys=True,+ separators=(",", ":"),+ )+ digest = hashlib.sha256(encoded.encode("utf-8")).hexdigest()+ return normalized, encoded, digest+++@dataclass(frozen=True)+class TaskIdentity:+ """Stable identity for one admitted room turn."""++ room_id: str+ task_id: str+ thread_id: str+ turn_id: str++ def __post_init__(self) -> None:+ for field in ("room_id", "task_id", "thread_id", "turn_id"):+ object.__setattr__(+ self,+ field,+ _identifier(getattr(self, field), label=field),+ )+++@dataclass(frozen=True)+class DriverLease:+ """A fenced lease held by one gateway process incarnation."""++ room_id: str+ gateway_id: str+ authority_epoch: int+ process_generation: str+ lease_generation: int+ expires_at: float+ reclaimed: bool = False+++@dataclass(frozen=True)+class TaskAttempt:+ """The exact running generation authorized to settle one task."""++ identity: TaskIdentity+ lease: DriverLease+ execution_generation: int+ cancel_generation: int+++def _create_task_table(+ conn: sqlite3.Connection, table: str = "hosted_room_driver_tasks"+) -> None:+ if table not in {"hosted_room_driver_tasks", "hosted_room_driver_tasks_next"}:+ raise DriverStateError("invalid hosted-room task table name")+ conn.execute(+ f"""CREATE TABLE IF NOT EXISTS {table} (+ room_id TEXT NOT NULL,+ task_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ turn_id TEXT NOT NULL,+ source_event_seq INTEGER NOT NULL CHECK (source_event_seq >= 1),+ payload_json TEXT NOT NULL,+ payload_digest TEXT NOT NULL,+ status TEXT NOT NULL CHECK (+ status IN (+ 'queued', 'running', 'settled', 'failed',+ 'cancelled', 'indeterminate', 'deferred', 'stopping'+ )+ ),+ execution_generation INTEGER NOT NULL DEFAULT 0+ CHECK (execution_generation >= 0),+ cancel_generation INTEGER NOT NULL DEFAULT 0+ CHECK (cancel_generation >= 0),+ run_gateway_id TEXT,+ run_process_generation TEXT,+ run_lease_generation INTEGER,+ cancel_id TEXT,+ settlement_id TEXT,+ settlement_status TEXT,+ result_json TEXT,+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ started_at REAL,+ terminal_at REAL,+ indeterminate_at REAL,+ PRIMARY KEY (room_id, task_id),+ UNIQUE (room_id, thread_id, turn_id),+ FOREIGN KEY (room_id) REFERENCES hosted_rooms(room_id)+ )"""+ )+++def _initialize_schema(conn: sqlite3.Connection) -> None:+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_driver_leases (+ room_id TEXT PRIMARY KEY,+ gateway_id TEXT NOT NULL,+ authority_epoch INTEGER NOT NULL CHECK (authority_epoch >= 1),+ process_generation TEXT NOT NULL,+ lease_generation INTEGER NOT NULL CHECK (lease_generation >= 1),+ expires_at REAL NOT NULL,+ acquired_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ released_at REAL,+ FOREIGN KEY (room_id) REFERENCES hosted_rooms(room_id)+ )"""+ )+ _create_task_table(conn)+ _validate_schema(conn)+ conn.execute(+ """CREATE INDEX IF NOT EXISTS idx_hosted_room_driver_tasks_status+ ON hosted_room_driver_tasks(+ room_id, status, source_event_seq, created_at, task_id+ )"""+ )+++def _validate_schema(conn: sqlite3.Connection) -> None:+ lease_columns = frozenset(+ row[1] for row in conn.execute("PRAGMA table_info(hosted_room_driver_leases)")+ )+ task_columns = frozenset(+ row[1] for row in conn.execute("PRAGMA table_info(hosted_room_driver_tasks)")+ )+ if lease_columns != _LEASE_COLUMNS or task_columns != _TASK_COLUMNS:+ raise DriverStateError(+ "unsupported unpublished hosted-room driver schema; "+ "recreate the driver tables before starting the driver"+ )++ for table in ("hosted_room_driver_leases", "hosted_room_driver_tasks"):+ foreign_keys = conn.execute(f"PRAGMA foreign_key_list({table})").fetchall()+ if not any(+ row[2] == "hosted_rooms" and row[3] == "room_id" and row[4] == "room_id"+ for row in foreign_keys+ ):+ raise DriverStateError(f"{table} is missing its hosted_rooms foreign key")+++def _schema_objects_exist(conn: sqlite3.Connection) -> bool:+ rows = conn.execute(+ """SELECT name FROM sqlite_master+ WHERE type='table' AND name IN (+ 'hosted_room_driver_leases', 'hosted_room_driver_tasks'+ )"""+ ).fetchall()+ tables = {row[0] for row in rows}+ if tables != {"hosted_room_driver_leases", "hosted_room_driver_tasks"}:+ return False+ index = conn.execute(+ """SELECT 1 FROM sqlite_master+ WHERE type='index' AND name='idx_hosted_room_driver_tasks_status'"""+ ).fetchone()+ return index is not None+++def _task_schema_supports_current_statuses(conn: sqlite3.Connection) -> bool:+ row = conn.execute(+ """SELECT sql FROM sqlite_master+ WHERE type='table' AND name='hosted_room_driver_tasks'"""+ ).fetchone()+ sql = str(row[0] or "").lower() if row else ""+ return "'stopping'" in sql and "'deferred'" in sql+++def _migrate_task_status_constraint(conn: sqlite3.Connection) -> None:+ """Expand the unpublished task-state CHECK without losing durable work."""+ conn.execute("DROP INDEX IF EXISTS idx_hosted_room_driver_tasks_status")+ _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"""+ )+ 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(+ """CREATE INDEX idx_hosted_room_driver_tasks_status+ ON hosted_room_driver_tasks(+ room_id, status, source_event_seq, created_at, task_id+ )"""+ )+++def _connect(db_path: Path | str) -> sqlite3.Connection:+ from hermes_state import apply_wal_with_fallback++ path = Path(db_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(path, timeout=10)+ conn.row_factory = sqlite3.Row+ try:+ apply_wal_with_fallback(conn, db_label="state.db (hosted_room_driver)")+ conn.execute("PRAGMA foreign_keys=ON")+ if _schema_objects_exist(conn):+ if not _task_schema_supports_current_statuses(conn):+ conn.execute("BEGIN IMMEDIATE")+ _migrate_task_status_constraint(conn)+ conn.commit()+ _validate_schema(conn)+ return conn+ # Schema creation is one database-wide transaction. The driver schema+ # has never shipped, so an incompatible draft schema fails closed+ # instead of attempting a partial in-place migration.+ conn.execute("BEGIN IMMEDIATE")+ _initialize_schema(conn)+ conn.commit()+ except Exception:+ conn.rollback()+ conn.close()+ raise+ return conn+++@contextmanager+def _transaction(db_path: Path | str) -> Iterator[sqlite3.Connection]:+ conn = _connect(db_path)+ try:+ conn.execute("BEGIN IMMEDIATE")+ yield conn+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()+++def _lease_from_row(+ row: sqlite3.Row | dict[str, Any], *, reclaimed: bool = False+) -> DriverLease:+ return DriverLease(+ room_id=row["room_id"],+ gateway_id=row["gateway_id"],+ authority_epoch=int(row["authority_epoch"]),+ process_generation=row["process_generation"],+ lease_generation=int(row["lease_generation"]),+ expires_at=float(row["expires_at"]),+ reclaimed=reclaimed,+ )+++def _task_identity_from_row(row: sqlite3.Row) -> TaskIdentity:+ return TaskIdentity(+ room_id=row["room_id"],+ task_id=row["task_id"],+ thread_id=row["thread_id"],+ turn_id=row["turn_id"],+ )+++def _task_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:+ try:+ raw_payload = json.loads(row["payload_json"])+ payload, encoded_payload, payload_digest = _task_payload(raw_payload)+ except (TypeError, json.JSONDecodeError, DriverValidationError) as exc:+ raise TaskConflictError("stored task payload is invalid") from exc+ if (+ encoded_payload != row["payload_json"]+ or payload_digest != row["payload_digest"]+ or payload["source_event_seq"] != int(row["source_event_seq"])+ ):+ raise TaskConflictError("stored task payload failed its integrity check")+ result = json.loads(row["result_json"]) if row["result_json"] is not None else None+ return {+ "identity": _task_identity_from_row(row),+ "payload": payload,+ "payload_digest": row["payload_digest"],+ "status": row["status"],+ "execution_generation": int(row["execution_generation"]),+ "cancel_generation": int(row["cancel_generation"]),+ "run_gateway_id": row["run_gateway_id"],+ "run_process_generation": row["run_process_generation"],+ "run_lease_generation": (+ int(row["run_lease_generation"])+ if row["run_lease_generation"] is not None+ else None+ ),+ "cancel_id": row["cancel_id"],+ "settlement_id": row["settlement_id"],+ "settlement_status": row["settlement_status"],+ "result": result,+ "created_at": float(row["created_at"]),+ "updated_at": float(row["updated_at"]),+ "started_at": (+ float(row["started_at"]) if row["started_at"] is not None else None+ ),+ "terminal_at": (+ float(row["terminal_at"]) if row["terminal_at"] is not None else None+ ),+ "indeterminate_at": (+ float(row["indeterminate_at"])+ if row["indeterminate_at"] is not None+ else None+ ),+ "idempotent": idempotent,+ }+++def _load_task(conn: sqlite3.Connection, identity: TaskIdentity) -> sqlite3.Row:+ row = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND task_id=?""",+ (identity.room_id, identity.task_id),+ ).fetchone()+ if row is None:+ raise TaskConflictError("task does not exist")+ if _task_identity_from_row(row) != identity:+ raise TaskConflictError("task_id is already bound to a different turn")+ return row+++def _load_active_room(conn: sqlite3.Connection, room_id: str) -> sqlite3.Row:+ try:+ row = conn.execute(+ """SELECT room_id, authority_gateway_id, authority_epoch, disbanded_at+ FROM hosted_rooms WHERE room_id=?""",+ (room_id,),+ ).fetchone()+ except sqlite3.OperationalError as exc:+ if "no such table" in str(exc).lower():+ raise RoomUnavailableError("hosted room does not exist") from exc+ raise+ if row is None:+ raise RoomUnavailableError("hosted room does not exist")+ if row["disbanded_at"] is not None:+ raise RoomUnavailableError("hosted room is disbanded")+ return row+++def _require_room_authority(+ conn: sqlite3.Connection,+ *,+ room_id: str,+ gateway_id: str,+ authority_epoch: int,+) -> sqlite3.Row:+ room = _load_active_room(conn, room_id)+ if (+ room["authority_gateway_id"] != gateway_id+ or int(room["authority_epoch"]) != authority_epoch+ ):+ raise StaleLeaseError("hosted room authority changed")+ return room+++def _require_active_lease(+ conn: sqlite3.Connection,+ lease: DriverLease,+ *,+ now: float,+) -> sqlite3.Row:+ _require_room_authority(+ conn,+ room_id=lease.room_id,+ gateway_id=lease.gateway_id,+ authority_epoch=lease.authority_epoch,+ )+ row = conn.execute(+ "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",+ (lease.room_id,),+ ).fetchone()+ if (+ row is None+ or row["gateway_id"] != lease.gateway_id+ or int(row["authority_epoch"]) != lease.authority_epoch+ or row["process_generation"] != lease.process_generation+ or int(row["lease_generation"]) != lease.lease_generation+ or row["released_at"] is not None+ or float(row["expires_at"]) <= now+ ):+ raise StaleLeaseError("driver lease is stale or expired")+ return row+++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:+ """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 = _authority_epoch(authority_epoch)+ process_generation = _identifier(+ process_generation,+ label="process_generation",+ )+ ttl_seconds = _ttl(ttl_seconds)+ now = _timestamp(clock)+ expires_at = _expiry(now, ttl_seconds)++ with _transaction(db_path) as conn:+ _require_room_authority(+ conn,+ room_id=room_id,+ gateway_id=gateway_id,+ authority_epoch=authority_epoch,+ )+ row = conn.execute(+ "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",+ (room_id,),+ ).fetchone()+ if row is None:+ conn.execute(+ """INSERT INTO hosted_room_driver_leases (+ room_id, gateway_id, authority_epoch, process_generation,+ lease_generation, expires_at, acquired_at,+ updated_at, released_at+ ) VALUES (?, ?, ?, ?, 1, ?, ?, ?, NULL)""",+ (+ room_id,+ gateway_id,+ authority_epoch,+ process_generation,+ expires_at,+ now,+ now,+ ),+ )+ row = conn.execute(+ "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",+ (room_id,),+ ).fetchone()+ return _lease_from_row(row)++ if (+ row["gateway_id"] == gateway_id+ and int(row["authority_epoch"]) == authority_epoch+ and row["process_generation"] == process_generation+ and row["released_at"] is None+ and float(row["expires_at"]) > now+ ):+ renewed_expiry = max(float(row["expires_at"]), expires_at)+ conn.execute(+ """UPDATE hosted_room_driver_leases+ SET expires_at=?, updated_at=?+ WHERE room_id=? AND lease_generation=?""",+ (renewed_expiry, now, room_id, int(row["lease_generation"])),+ )+ current = dict(row)+ current["expires_at"] = renewed_expiry+ return _lease_from_row(current)++ same_authority = (+ row["gateway_id"] == gateway_id+ and int(row["authority_epoch"]) == authority_epoch+ )+ if (+ same_authority+ and row["released_at"] is None+ and float(row["expires_at"]) > now+ ):+ raise LeaseHeldError("room driver lease is held by another generation")++ previous_generation = int(row["lease_generation"])+ updated = conn.execute(+ """UPDATE hosted_room_driver_leases+ SET gateway_id=?, authority_epoch=?, process_generation=?,+ lease_generation=lease_generation + 1,+ expires_at=?, acquired_at=?, updated_at=?, released_at=NULL+ WHERE room_id=? AND lease_generation=?+ AND (+ gateway_id != ? OR authority_epoch != ?+ OR released_at IS NOT NULL OR expires_at <= ?+ )""",+ (+ gateway_id,+ authority_epoch,+ process_generation,+ expires_at,+ now,+ now,+ room_id,+ previous_generation,+ gateway_id,+ authority_epoch,+ now,+ ),+ )+ if updated.rowcount != 1:+ raise LeaseHeldError("room driver lease changed during acquisition")+ current = conn.execute(+ "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",+ (room_id,),+ ).fetchone()+ return _lease_from_row(current, reclaimed=True)+++def renew_lease(+ db_path: Path | str,+ 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)+ requested_expiry = _expiry(now, ttl_seconds)+ with _transaction(db_path) as conn:+ current = _require_active_lease(conn, lease, now=now)+ expires_at = max(float(current["expires_at"]), requested_expiry)+ updated = conn.execute(+ """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,+ ),+ )+ if updated.rowcount != 1:+ raise StaleLeaseError("driver lease changed during renewal")+ return DriverLease(+ room_id=lease.room_id,+ gateway_id=lease.gateway_id,+ authority_epoch=lease.authority_epoch,+ process_generation=lease.process_generation,+ lease_generation=lease.lease_generation,+ expires_at=expires_at,+ )+++def release_lease(+ db_path: Path | str,+ lease: DriverLease,+ *,+ clock: Clock,+) -> dict[str, Any]:+ """Release the exact active lease generation idempotently."""+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_room_authority(+ conn,+ room_id=lease.room_id,+ gateway_id=lease.gateway_id,+ authority_epoch=lease.authority_epoch,+ )+ row = conn.execute(+ "SELECT * FROM hosted_room_driver_leases WHERE room_id=?",+ (lease.room_id,),+ ).fetchone()+ if (+ row is None+ or row["gateway_id"] != lease.gateway_id+ or int(row["authority_epoch"]) != lease.authority_epoch+ or row["process_generation"] != lease.process_generation+ or int(row["lease_generation"]) != lease.lease_generation+ ):+ raise StaleLeaseError("driver lease is stale")+ if row["released_at"] is not None:+ return {"lease": _lease_from_row(row), "idempotent": True}+ if float(row["expires_at"]) <= now:+ raise StaleLeaseError("driver lease expired before release")+ running = conn.execute(+ """SELECT 1 FROM hosted_room_driver_tasks+ WHERE room_id=? AND status='running' LIMIT 1""",+ (lease.room_id,),+ ).fetchone()+ if running is not None:+ raise InvalidTaskTransitionError(+ "cannot release a room lease while tasks are running"+ )+ conn.execute(+ """UPDATE hosted_room_driver_leases+ SET expires_at=?, updated_at=?, released_at=?+ WHERE room_id=? AND lease_generation=?""",+ (now, now, now, lease.room_id, lease.lease_generation),+ )+ current = dict(row)+ current["expires_at"] = now+ current["updated_at"] = now+ current["released_at"] = now+ return {"lease": _lease_from_row(current), "idempotent": False}+++def admit_task(+ db_path: Path | str,+ 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)+ with _transaction(db_path) as conn:+ _load_active_room(conn, identity.room_id)+ existing = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND task_id=?""",+ (identity.room_id, identity.task_id),+ ).fetchone()+ if existing is not None:+ if _task_identity_from_row(existing) != identity:+ raise TaskConflictError("task_id is already bound to a different turn")+ if (+ existing["payload_digest"] != payload_digest+ or existing["payload_json"] != payload_json+ ):+ raise TaskConflictError(+ "task_id is already bound to a different payload"+ )+ return _task_from_row(existing, idempotent=True)++ turn = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND thread_id=? AND turn_id=?""",+ (identity.room_id, identity.thread_id, identity.turn_id),+ ).fetchone()+ if turn is not None:+ raise TaskConflictError("thread_id and turn_id are already bound to a task")++ conn.execute(+ """INSERT INTO hosted_room_driver_tasks (+ room_id, task_id, thread_id, turn_id,+ source_event_seq, payload_json, payload_digest, status,+ execution_generation, cancel_generation,+ created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', 0, 0, ?, ?)""",+ (+ identity.room_id,+ identity.task_id,+ identity.thread_id,+ identity.turn_id,+ normalized_payload["source_event_seq"],+ payload_json,+ payload_digest,+ now,+ now,+ ),+ )+ row = _load_task(conn, identity)+ return _task_from_row(row)+++def start_task(+ db_path: Path | str,+ identity: TaskIdentity,+ lease: DriverLease,+ *,+ expected_cancel_generation: int,+ clock: Clock,+) -> TaskAttempt:+ """Move one queued task to running under the current driver lease."""+ if lease.room_id != identity.room_id:+ raise DriverValidationError("lease and task belong to different rooms")+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ row = _load_task(conn, identity)+ if int(row["cancel_generation"]) != expected_cancel_generation:+ raise StaleTaskError("task cancellation generation changed")+ if row["status"] != "queued":+ raise InvalidTaskTransitionError(+ f"cannot start task in state '{row['status']}'"+ )+ unresolved = conn.execute(+ """SELECT task_id, status FROM hosted_room_driver_tasks+ WHERE room_id=? AND status IN ('running', 'indeterminate', 'stopping')+ ORDER BY source_event_seq, created_at, task_id LIMIT 1""",+ (identity.room_id,),+ ).fetchone()+ if unresolved is not None:+ raise InvalidTaskTransitionError(+ "room recovery must resolve the prior task before starting new work"+ )+ next_queued = conn.execute(+ """SELECT task_id FROM hosted_room_driver_tasks+ WHERE room_id=? AND status='queued'+ ORDER BY source_event_seq, created_at, task_id LIMIT 1""",+ (identity.room_id,),+ ).fetchone()+ if next_queued is None or next_queued["task_id"] != identity.task_id:+ raise InvalidTaskTransitionError(+ "task is not next in the hosted room event order"+ )+ execution_generation = int(row["execution_generation"]) + 1+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='running', execution_generation=?,+ run_gateway_id=?, run_process_generation=?,+ run_lease_generation=?, started_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='queued'+ AND cancel_generation=?""",+ (+ execution_generation,+ lease.gateway_id,+ lease.process_generation,+ lease.lease_generation,+ now,+ now,+ identity.room_id,+ identity.task_id,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task changed during start")+ return TaskAttempt(+ identity=identity,+ lease=lease,+ execution_generation=execution_generation,+ cancel_generation=expected_cancel_generation,+ )+++def settle_task(+ db_path: Path | str,+ 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 = _identifier(settlement_id, label="settlement_id")+ if status not in {"settled", "failed"}:+ raise DriverValidationError("status must be 'settled' or 'failed'")+ result_json = _canonical_json(result)+ now = _timestamp(clock)++ with _transaction(db_path) as conn:+ row = _load_task(conn, attempt.identity)+ if row["settlement_id"] is not None:+ if (+ row["settlement_id"] == settlement_id+ and row["settlement_status"] == status+ and row["result_json"] == result_json+ ):+ return _task_from_row(row, idempotent=True)+ raise TaskConflictError("task already has a different terminal settlement")++ _require_active_lease(conn, attempt.lease, now=now)+ expected = (+ row["status"] == "running"+ and int(row["execution_generation"]) == attempt.execution_generation+ and int(row["cancel_generation"]) == attempt.cancel_generation+ and row["run_gateway_id"] == attempt.lease.gateway_id+ and row["run_process_generation"] == attempt.lease.process_generation+ and int(row["run_lease_generation"]) == attempt.lease.lease_generation+ )+ if not expected:+ raise StaleTaskError("task attempt is stale or cancelled")++ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status=?, settlement_id=?, settlement_status=?,+ result_json=?, terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='running'+ AND execution_generation=? AND cancel_generation=?+ AND run_gateway_id=? AND run_process_generation=?+ AND run_lease_generation=?""",+ (+ status,+ settlement_id,+ status,+ result_json,+ now,+ now,+ attempt.identity.room_id,+ attempt.identity.task_id,+ attempt.execution_generation,+ attempt.cancel_generation,+ attempt.lease.gateway_id,+ attempt.lease.process_generation,+ attempt.lease.lease_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task changed during settlement")+ return _task_from_row(_load_task(conn, attempt.identity))+++def settle_stopping_task(+ db_path: Path | str,+ 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."""+ settlement_id = _identifier(settlement_id, label="settlement_id")+ if status not in {"settled", "failed"}:+ raise DriverValidationError("status must be 'settled' or 'failed'")+ if expected_execution_generation < 1 or expected_cancel_generation < 1:+ raise DriverValidationError("stopping settlement generations are invalid")+ result_json = _canonical_json(result)+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ row = _load_task(conn, identity)+ if row["settlement_id"] is not None:+ if (+ row["settlement_id"] == settlement_id+ and row["settlement_status"] == status+ and row["result_json"] == result_json+ ):+ return _task_from_row(row, idempotent=True)+ raise TaskConflictError("task already has a different terminal settlement")+ _require_active_lease(conn, lease, now=now)+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status=?, settlement_id=?, settlement_status=?,+ result_json=?, terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='stopping'+ AND execution_generation=? AND cancel_generation=?""",+ (+ status,+ settlement_id,+ status,+ result_json,+ now,+ now,+ identity.room_id,+ identity.task_id,+ expected_execution_generation,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task completion lost the stop race")+ return _task_from_row(_load_task(conn, identity))+++def resolve_indeterminate_task(+ db_path: Path | str,+ 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."""+ if lease.room_id != identity.room_id:+ raise DriverValidationError("lease and task belong to different rooms")+ if (+ not isinstance(expected_execution_generation, int)+ or expected_execution_generation < 1+ ):+ raise DriverValidationError(+ "expected_execution_generation must be a positive integer"+ )+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ settlement_id = _identifier(settlement_id, label="settlement_id")+ if status not in {"settled", "failed"}:+ raise DriverValidationError("status must be 'settled' or 'failed'")+ result_json = _canonical_json(result)+ now = _timestamp(clock)++ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ row = _load_task(conn, identity)+ if row["settlement_id"] is not None:+ if (+ row["settlement_id"] == settlement_id+ and row["settlement_status"] == status+ and row["result_json"] == result_json+ ):+ return _task_from_row(row, idempotent=True)+ raise TaskConflictError("task already has a different terminal settlement")+ if (+ row["status"] != "indeterminate"+ or int(row["execution_generation"]) != expected_execution_generation+ or int(row["cancel_generation"]) != expected_cancel_generation+ ):+ raise StaleTaskError("indeterminate task generation changed")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status=?, settlement_id=?, settlement_status=?,+ result_json=?, terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='indeterminate'+ AND execution_generation=? AND cancel_generation=?""",+ (+ status,+ settlement_id,+ status,+ result_json,+ now,+ now,+ identity.room_id,+ identity.task_id,+ expected_execution_generation,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("indeterminate task changed during reconciliation")+ return _task_from_row(_load_task(conn, identity))+++def requeue_indeterminate_task(+ db_path: Path | str,+ 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."""+ if lease.room_id != identity.room_id:+ raise DriverValidationError("lease and task belong to different rooms")+ if (+ not isinstance(expected_execution_generation, int)+ or expected_execution_generation < 1+ ):+ raise DriverValidationError(+ "expected_execution_generation must be a positive integer"+ )+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ row = _load_task(conn, identity)+ if (+ row["status"] != "indeterminate"+ or int(row["execution_generation"]) != expected_execution_generation+ or int(row["cancel_generation"]) != expected_cancel_generation+ ):+ raise StaleTaskError("indeterminate task generation changed")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='queued', run_gateway_id=NULL,+ run_process_generation=NULL, run_lease_generation=NULL,+ started_at=NULL, indeterminate_at=NULL, updated_at=?+ WHERE room_id=? AND task_id=? AND status='indeterminate'+ AND execution_generation=? AND cancel_generation=?""",+ (+ now,+ identity.room_id,+ identity.task_id,+ expected_execution_generation,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("indeterminate task changed during requeue")+ return _task_from_row(_load_task(conn, identity))+++def defer_indeterminate_task(+ db_path: Path | str,+ 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."""++ if lease.room_id != identity.room_id:+ raise DriverValidationError("lease and task belong to different rooms")+ if (+ not isinstance(expected_execution_generation, int)+ or expected_execution_generation < 1+ ):+ raise DriverValidationError(+ "expected_execution_generation must be a positive integer"+ )+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ reason = _identifier(reason, label="defer_reason")+ result_json = _canonical_json({"reason": reason, "retryable": True})+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ row = _load_task(conn, identity)+ if (+ row["status"] == "deferred"+ and int(row["execution_generation"]) == expected_execution_generation+ and int(row["cancel_generation"]) == expected_cancel_generation+ and row["result_json"] == result_json+ ):+ return _task_from_row(row, idempotent=True)+ if (+ row["status"] != "indeterminate"+ or int(row["execution_generation"]) != expected_execution_generation+ or int(row["cancel_generation"]) != expected_cancel_generation+ ):+ raise StaleTaskError("indeterminate task generation changed")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='deferred', result_json=?, terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='indeterminate'+ AND execution_generation=? AND cancel_generation=?""",+ (+ result_json,+ now,+ now,+ identity.room_id,+ identity.task_id,+ expected_execution_generation,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("indeterminate task changed during deferral")+ return _task_from_row(_load_task(conn, identity))+++def requeue_deferred_task(+ db_path: Path | str,+ 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."""++ if lease.room_id != identity.room_id:+ raise DriverValidationError("lease and task belong to different rooms")+ if (+ not isinstance(expected_execution_generation, int)+ or expected_execution_generation < 1+ ):+ raise DriverValidationError(+ "expected_execution_generation must be a positive integer"+ )+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ row = _load_task(conn, identity)+ if (+ row["status"] != "deferred"+ or int(row["execution_generation"]) != expected_execution_generation+ or int(row["cancel_generation"]) != expected_cancel_generation+ ):+ raise StaleTaskError("deferred task generation changed")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='queued', run_gateway_id=NULL,+ run_process_generation=NULL, run_lease_generation=NULL,+ result_json=NULL, started_at=NULL, terminal_at=NULL,+ indeterminate_at=NULL, updated_at=?+ WHERE room_id=? AND task_id=? AND status='deferred'+ AND execution_generation=? AND cancel_generation=?""",+ (+ now,+ identity.room_id,+ identity.task_id,+ expected_execution_generation,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("deferred task changed during requeue")+ return _task_from_row(_load_task(conn, identity))+++def cancel_task(+ db_path: Path | str,+ 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")+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ row = _load_task(conn, identity)+ if row["status"] == "cancelled" and row["cancel_id"] == cancel_id:+ return _task_from_row(row, idempotent=True)+ if row["status"] in TERMINAL_STATUSES:+ raise InvalidTaskTransitionError(+ f"cannot cancel task in state '{row['status']}'"+ )+ if row["status"] not in {"queued", "deferred"}:+ raise InvalidTaskTransitionError(+ "running work requires acknowledged two-phase cancellation"+ )+ if int(row["cancel_generation"]) != expected_cancel_generation:+ raise StaleTaskError("task cancellation generation changed")++ next_generation = expected_cancel_generation + 1+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='cancelled', cancel_generation=?, cancel_id=?,+ terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=?+ AND status IN ('queued', 'deferred')+ AND cancel_generation=?""",+ (+ next_generation,+ cancel_id,+ now,+ now,+ identity.room_id,+ identity.task_id,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task changed during cancellation")+ return _task_from_row(_load_task(conn, identity))+++def begin_task_cancel(+ db_path: Path | str,+ 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")+ if (+ not isinstance(expected_cancel_generation, int)+ or expected_cancel_generation < 0+ ):+ raise DriverValidationError("expected_cancel_generation must be non-negative")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ row = _load_task(conn, identity)+ if row["status"] == "stopping" and row["cancel_id"] == cancel_id:+ return _task_from_row(row, idempotent=True)+ if row["status"] in TERMINAL_STATUSES or row["status"] == "queued":+ raise InvalidTaskTransitionError(+ f"cannot request remote stop in state '{row['status']}'"+ )+ if int(row["cancel_generation"]) != expected_cancel_generation:+ raise StaleTaskError("task cancellation generation changed")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='stopping', cancel_generation=?, cancel_id=?,+ updated_at=?+ WHERE room_id=? AND task_id=?+ AND status IN ('running', 'indeterminate')+ AND cancel_generation=?""",+ (+ expected_cancel_generation + 1,+ cancel_id,+ now,+ identity.room_id,+ identity.task_id,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task changed during stop request")+ return _task_from_row(_load_task(conn, identity))+++def complete_task_cancel(+ db_path: Path | str,+ 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")+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ row = _load_task(conn, identity)+ if row["status"] == "cancelled" and row["cancel_id"] == cancel_id:+ return _task_from_row(row, idempotent=True)+ if (+ row["status"] != "stopping"+ or row["cancel_id"] != cancel_id+ or int(row["cancel_generation"]) != expected_cancel_generation+ ):+ raise StaleTaskError("task stop acknowledgement is stale")+ updated = conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='cancelled', terminal_at=?, updated_at=?+ WHERE room_id=? AND task_id=? AND status='stopping'+ AND cancel_id=? AND cancel_generation=?""",+ (+ now,+ now,+ identity.room_id,+ identity.task_id,+ cancel_id,+ expected_cancel_generation,+ ),+ )+ if updated.rowcount != 1:+ raise StaleTaskError("task changed during stop acknowledgement")+ return _task_from_row(_load_task(conn, identity))+++def recover_room(+ db_path: Path | str,+ lease: DriverLease,+ *,+ clock: Clock,+) -> dict[str, list[TaskIdentity]]:+ """Fence abandoned running attempts without requeueing uncertain work."""+ now = _timestamp(clock)+ with _transaction(db_path) as conn:+ _require_active_lease(conn, lease, now=now)+ stale_rows = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND status='running'+ AND NOT (+ run_gateway_id=? AND run_process_generation=?+ AND run_lease_generation=?+ )+ ORDER BY source_event_seq, created_at, task_id""",+ (+ lease.room_id,+ lease.gateway_id,+ lease.process_generation,+ lease.lease_generation,+ ),+ ).fetchall()+ if stale_rows:+ conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET status='indeterminate', indeterminate_at=?, updated_at=?+ WHERE room_id=? AND status='running'+ AND NOT (+ run_gateway_id=? AND run_process_generation=?+ AND run_lease_generation=?+ )""",+ (+ now,+ now,+ lease.room_id,+ lease.gateway_id,+ lease.process_generation,+ lease.lease_generation,+ ),+ )+ queued_rows = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND status='queued'+ ORDER BY source_event_seq, created_at, task_id""",+ (lease.room_id,),+ ).fetchall()+ indeterminate_rows = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND status='indeterminate'+ ORDER BY source_event_seq, created_at, task_id""",+ (lease.room_id,),+ ).fetchall()+ return {+ "queued": [_task_identity_from_row(row) for row in queued_rows],+ "indeterminate": [+ _task_identity_from_row(row) for row in indeterminate_rows+ ],+ }+++def get_task(+ db_path: Path | str,+ identity: TaskIdentity,+) -> dict[str, Any]:+ """Read one task without mutating its state."""+ conn = _connect(db_path)+ try:+ return _task_from_row(_load_task(conn, identity))+ finally:+ conn.close()+++def list_tasks(+ db_path: Path | str,+ *,+ 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:+ raise DriverValidationError("invalid task status")+ conn = _connect(db_path)+ try:+ if status is None:+ rows = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=?+ ORDER BY source_event_seq, created_at, task_id""",+ (room_id,),+ ).fetchall()+ else:+ rows = conn.execute(+ """SELECT * FROM hosted_room_driver_tasks+ WHERE room_id=? AND status=?+ ORDER BY source_event_seq, created_at, task_id""",+ (room_id, status),+ ).fetchall()+ return [_task_from_row(row) for row in rows]+ finally:+ conn.close()+++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:+ """Bound execution rows after outcomes are durable in the room log."""++ room_id = _identifier(room_id, label="room_id")+ now = _timestamp(clock)+ if retention_seconds <= 0:+ raise DriverValidationError("retention_seconds must be positive")+ if isinstance(retain, bool) or not isinstance(retain, int) or retain < 0:+ raise DriverValidationError("retain must be a non-negative integer")++ with _transaction(db_path) as conn:+ publications = conn.execute(+ """SELECT 1 FROM sqlite_master+ WHERE type='table' AND name='hosted_room_policy_publications'"""+ ).fetchone()+ if publications is None:+ return 0+ rows = conn.execute(+ """SELECT t.task_id, t.terminal_at+ FROM hosted_room_driver_tasks t+ WHERE t.room_id=?+ AND t.status IN ('settled', 'failed', 'cancelled')+ AND EXISTS (+ SELECT 1 FROM hosted_room_policy_publications p+ WHERE p.room_id=t.room_id AND p.task_id=t.task_id+ AND p.kind IN (+ 'turn.settled', 'turn.failed', 'turn.cancelled'+ )+ )+ ORDER BY t.terminal_at DESC, t.task_id ASC""",+ (room_id,),+ ).fetchall()+ cutoff = now - float(retention_seconds)+ candidates = [+ str(row["task_id"])+ for index, row in enumerate(rows)+ if index >= retain+ or (row["terminal_at"] is not None and float(row["terminal_at"]) <= cutoff)+ ][:MAX_TASK_PRUNE_BATCH]+ if not candidates:+ return 0+ placeholders = ",".join("?" for _ in candidates)+ deleted = conn.execute(+ f"""DELETE FROM hosted_room_driver_tasks+ WHERE room_id=? AND task_id IN ({placeholders})""",+ (room_id, *candidates),+ )+ return max(0, int(deleted.rowcount))diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pynew file mode 100644index 00000000000..e141b0e158e--- /dev/null+++ b/gateway/hosted_room_policy_checkpoint.py@@ -0,0 +1,682 @@+"""Durable bounded policy projection for hosted Group Chat preparation.++The append-only room log remains the user-visible source of truth. This module+materializes only the state needed to choose and reconstruct the next active+discussion, so a busy room does not replay its complete history every poll.+"""++from __future__ import annotations++import json+import sqlite3+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Mapping++from gateway import hosted_rooms+++MAX_ACTIVE_POLICY_EVENTS = 64+MAX_THREAD_TRANSCRIPT_EVENTS = 24+_TRANSCRIPT_SCHEMA_VERSION = 1+_TERMINAL_KINDS = frozenset({+ "turn.settled",+ "turn.failed",+ "turn.cancelled",+ "turn.deferred",+})+++@dataclass(frozen=True)+class PolicySnapshot:+ """Bounded active policy input at one durable room-log cursor."""++ through_seq: int+ stopped_through_seq: int+ events: tuple[dict[str, Any], ...]+ watermarks: Mapping[tuple[str, str], int]+++class HostedRoomPolicyCheckpoint:+ """Incrementally index room policy without compacting visible history."""++ def __init__(self, db_path: Path | str) -> None:+ self.db_path = Path(db_path)+ self._initialize()++ def _connect(self) -> sqlite3.Connection:+ from hermes_state import apply_wal_with_fallback++ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(self.db_path, timeout=10)+ conn.row_factory = sqlite3.Row+ apply_wal_with_fallback(conn, db_label="state.db (room policy checkpoint)")+ return conn++ def _initialize(self) -> None:+ with self._connect() as conn:+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_cursors (+ room_id TEXT PRIMARY KEY,+ through_seq INTEGER NOT NULL DEFAULT 0,+ stopped_through_seq INTEGER NOT NULL DEFAULT 0,+ updated_at REAL NOT NULL DEFAULT 0+ )"""+ )+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_threads (+ room_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ discussion_event_id TEXT NOT NULL,+ latest_user_seq INTEGER NOT NULL,+ completed INTEGER NOT NULL DEFAULT 0,+ PRIMARY KEY(room_id, thread_id)+ )"""+ )+ conn.execute(+ """CREATE INDEX IF NOT EXISTS idx_hosted_room_policy_pending+ ON hosted_room_policy_threads(+ room_id, completed, latest_user_seq, thread_id+ )"""+ )+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_events (+ room_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ discussion_event_id TEXT NOT NULL,+ seq INTEGER NOT NULL,+ event_json TEXT NOT NULL,+ PRIMARY KEY(room_id, seq)+ )"""+ )+ conn.execute(+ """CREATE INDEX IF NOT EXISTS idx_hosted_room_policy_events_active+ ON hosted_room_policy_events(+ room_id, discussion_event_id, seq+ )"""+ )+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_watermarks (+ room_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ member_id TEXT NOT NULL,+ seen_through_seq INTEGER NOT NULL,+ PRIMARY KEY(room_id, thread_id, member_id)+ )"""+ )+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_publications (+ room_id TEXT NOT NULL,+ task_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ execution_generation INTEGER NOT NULL DEFAULT 0,+ seq INTEGER NOT NULL,+ PRIMARY KEY(room_id, task_id, kind, execution_generation)+ )"""+ )+ conn.execute(+ # Store only references into the already bounded room log. This+ # avoids duplicating prompt payloads outside room byte limits.+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_transcript (+ room_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ seq INTEGER NOT NULL,+ kind TEXT NOT NULL,+ settled_seq INTEGER,+ PRIMARY KEY(room_id, thread_id, seq)+ )"""+ )+ conn.execute(+ """CREATE TABLE IF NOT EXISTS hosted_room_policy_transcript_state (+ room_id TEXT PRIMARY KEY,+ schema_version INTEGER NOT NULL+ )"""+ )++ @staticmethod+ def _event_json(event: Mapping[str, Any]) -> str:+ return json.dumps(+ dict(event),+ ensure_ascii=True,+ sort_keys=True,+ separators=(",", ":"),+ )++ def _store_active_event(+ self,+ 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+ ) VALUES (?, ?, ?, ?, ?)""",+ (+ event["room_id"],+ thread_id,+ discussion_event_id,+ int(event["seq"]),+ self._event_json(event),+ ),+ )++ def _store_transcript_event(+ self,+ 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+ ) VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(room_id, thread_id, seq) DO UPDATE SET+ settled_seq=COALESCE(+ excluded.settled_seq,+ hosted_room_policy_transcript.settled_seq+ )""",+ (+ event["room_id"],+ thread_id,+ int(event["seq"]),+ str(event["kind"]),+ settled_seq,+ ),+ )+ if event["kind"] in {"message.user", "message.member"}:+ cutoff = conn.execute(+ """SELECT seq FROM hosted_room_policy_transcript+ WHERE room_id=? AND thread_id=?+ AND kind IN ('message.user', 'message.member')+ ORDER BY seq DESC LIMIT 1 OFFSET ?""",+ (+ event["room_id"],+ thread_id,+ MAX_THREAD_TRANSCRIPT_EVENTS - 1,+ ),+ ).fetchone()+ if cutoff is not None:+ conn.execute(+ """DELETE FROM hosted_room_policy_transcript+ WHERE room_id=? AND thread_id=? AND seq<?""",+ (event["room_id"], thread_id, int(cutoff["seq"])),+ )++ @staticmethod+ def _event_from_room_row(row: sqlite3.Row) -> dict[str, Any]:+ return {+ "room_id": str(row["room_id"]),+ "seq": int(row["seq"]),+ "event_id": str(row["event_id"]),+ "kind": str(row["kind"]),+ "actor": json.loads(row["actor_json"]),+ "authority_epoch": row["authority_epoch"],+ "payload": json.loads(row["payload_json"]),+ "created_at": float(row["created_at"]),+ "idempotent": False,+ }++ def _backfill_transcript(+ self,+ conn: sqlite3.Connection,+ *,+ room_id: str,+ through_seq: int,+ ) -> None:+ """Migrate bounded committed thread history from the durable room log."""++ if through_seq <= 0:+ return+ settled_seq_by_message: dict[str, int] = {}+ for row in conn.execute(+ """SELECT seq, payload_json FROM hosted_room_events+ WHERE room_id=? AND seq<=? AND kind='turn.settled'+ ORDER BY seq""",+ (room_id, through_seq),+ ):+ message_event_id = str(+ json.loads(row["payload_json"]).get("message_event_id") or ""+ )+ if message_event_id:+ settled_seq_by_message[message_event_id] = int(row["seq"])+ rows = conn.execute(+ """SELECT room_id, seq, event_id, kind, actor_json,+ authority_epoch, payload_json, created_at+ FROM hosted_room_events+ WHERE room_id=? AND seq<=?+ AND kind IN ('message.user', 'message.member')+ ORDER BY seq""",+ (room_id, through_seq),+ )+ for row in rows:+ if (+ row["kind"] == "message.member"+ and row["event_id"] not in settled_seq_by_message+ ):+ continue+ event = self._event_from_room_row(row)+ thread_id = str(event["payload"].get("thread_id") or "")+ if thread_id:+ self._store_transcript_event(+ conn,+ event=event,+ thread_id=thread_id,+ settled_seq=settled_seq_by_message.get(str(row["event_id"])),+ )++ def _transcript_events(+ self,+ conn: sqlite3.Connection,+ *,+ room_id: str,+ thread_id: str,+ ) -> list[dict[str, Any]]:+ rows = conn.execute(+ """WITH transcript_events(seq) AS (+ SELECT seq FROM hosted_room_policy_transcript+ WHERE room_id=? AND thread_id=?+ UNION ALL+ SELECT settled_seq FROM hosted_room_policy_transcript+ WHERE room_id=? AND thread_id=? AND settled_seq IS NOT NULL+ )+ SELECT events.room_id, events.seq, events.event_id,+ events.kind, events.actor_json,+ events.authority_epoch, events.payload_json,+ events.created_at+ FROM transcript_events+ JOIN hosted_room_events AS events+ ON events.room_id=? AND events.seq=transcript_events.seq+ ORDER BY events.seq""",+ (room_id, thread_id, room_id, thread_id, room_id),+ ).fetchall()+ return [self._event_from_room_row(row) for row in rows]++ def _apply_event(self, conn: sqlite3.Connection, event: Mapping[str, Any]) -> None:+ room_id = str(event["room_id"])+ seq = int(event["seq"])+ kind = str(event.get("kind") or "")+ payload = event.get("payload")+ payload = payload if isinstance(payload, Mapping) else {}++ if kind == "message.user":+ thread_id = str(payload.get("thread_id") or "")+ event_id = str(event.get("event_id") or "")+ if not thread_id or not event_id:+ return+ conn.execute(+ """INSERT INTO hosted_room_policy_threads(+ room_id, thread_id, discussion_event_id,+ latest_user_seq, completed+ ) VALUES (?, ?, ?, ?, 0)+ ON CONFLICT(room_id, thread_id) DO UPDATE SET+ discussion_event_id=excluded.discussion_event_id,+ latest_user_seq=excluded.latest_user_seq,+ completed=0""",+ (room_id, thread_id, event_id, seq),+ )+ self._store_active_event(+ conn,+ event=event,+ thread_id=thread_id,+ discussion_event_id=event_id,+ )+ self._store_transcript_event(+ conn,+ event=event,+ thread_id=thread_id,+ )+ return++ if kind in {"message.member", *_TERMINAL_KINDS}:+ thread_id = str(payload.get("thread_id") or "")+ discussion_event_id = str(payload.get("discussion_event_id") or "")+ source = conn.execute(+ """SELECT 1 FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=? LIMIT 1""",+ (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,+ )+ if kind in _TERMINAL_KINDS:+ task_id = str(payload.get("task_id") or "")+ 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(+ room_id, task_id, kind, execution_generation, seq+ ) VALUES (?, ?, ?, ?, ?)""",+ (+ room_id,+ task_id,+ kind,+ execution_generation,+ seq,+ ),+ )+ member_id = str(payload.get("member_id") or "")+ seen_through_seq = int(payload.get("seen_through_seq") or 0)+ if kind == "turn.settled" and payload.get("message_event_id"):+ messages = conn.execute(+ """SELECT seq, event_json FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=?""",+ (room_id, discussion_event_id),+ ).fetchall()+ decoded_messages = [+ json.loads(message["event_json"])+ for message in messages+ ]+ committed = next(+ (+ message+ for message in decoded_messages+ if message.get("event_id")+ == payload["message_event_id"]+ ),+ None,+ )+ if committed is not None:+ seen_through_seq = max(+ seen_through_seq,+ int(committed["seq"]),+ )+ self._store_transcript_event(+ conn,+ event=committed,+ thread_id=thread_id,+ settled_seq=int(event["seq"]),+ )+ if member_id and seen_through_seq > 0:+ conn.execute(+ """INSERT INTO hosted_room_policy_watermarks(+ room_id, thread_id, member_id, seen_through_seq+ ) VALUES (?, ?, ?, ?)+ ON CONFLICT(room_id, thread_id, member_id) DO UPDATE SET+ seen_through_seq=MAX(+ hosted_room_policy_watermarks.seen_through_seq,+ excluded.seen_through_seq+ )""",+ (room_id, thread_id, member_id, seen_through_seq),+ )+ return++ if kind == "room.activity":+ thread_id = str(payload.get("thread_id") or "")+ discussion_event_id = str(payload.get("discussion_event_id") or "")+ conn.execute(+ """DELETE FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=?""",+ (room_id, discussion_event_id),+ )+ conn.execute(+ """DELETE FROM hosted_room_policy_threads+ WHERE room_id=? AND thread_id=?""",+ (room_id, thread_id),+ )+ return++ if kind == "room.stop_requested":+ conn.execute(+ """UPDATE hosted_room_policy_cursors+ SET stopped_through_seq=MAX(stopped_through_seq, ?)+ WHERE room_id=?""",+ (seq, room_id),+ )++ def sync(self, *, room_id: str, latest_seq: int) -> int:+ """Materialize each unseen event exactly once by durable cursor."""++ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ if conn.execute(+ "SELECT 1 FROM hosted_rooms WHERE room_id=?",+ (room_id,),+ ).fetchone() is None:+ raise hosted_rooms.RoomNotFoundError("hosted room not found")+ conn.execute(+ """INSERT OR IGNORE INTO hosted_room_policy_cursors(+ 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()+ cursor = int(row["through_seq"])+ transcript_state = conn.execute(+ """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(+ """INSERT INTO hosted_room_policy_transcript_state(+ room_id, schema_version+ ) VALUES (?, ?)+ ON CONFLICT(room_id) DO UPDATE SET+ schema_version=excluded.schema_version""",+ (room_id, _TRANSCRIPT_SCHEMA_VERSION),+ )+ if cursor > latest_seq:+ raise RuntimeError("room policy cursor is ahead of the durable log")++ while cursor < latest_seq:+ page = hosted_rooms.read_events(+ self.db_path,+ room_id=room_id,+ since_seq=cursor,+ limit=hosted_rooms.MAX_LOG_LIMIT,+ )+ rows = [+ event for event in page.get("events", []) if isinstance(event, Mapping)+ ]+ next_cursor = int(page.get("cursor") or cursor)+ if not rows or next_cursor <= cursor:+ raise RuntimeError("hosted room policy cursor did not advance")+ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ if conn.execute(+ "SELECT 1 FROM hosted_rooms WHERE room_id=?",+ (room_id,),+ ).fetchone() is None:+ raise hosted_rooms.RoomNotFoundError("hosted room not found")+ for event in rows:+ self._apply_event(conn, event)+ updated = conn.execute(+ """UPDATE hosted_room_policy_cursors+ SET through_seq=?, updated_at=? WHERE room_id=?""",+ (+ next_cursor,+ float(rows[-1].get("created_at") or 0),+ room_id,+ ),+ )+ if updated.rowcount != 1:+ raise RuntimeError("room policy cursor disappeared during replay")+ cursor = next_cursor+ return cursor++ def snapshot(self, *, room_id: str, latest_seq: int) -> PolicySnapshot:+ """Return only the oldest active discussion and its watermark set."""++ 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()+ stopped_through_seq = int(cursor["stopped_through_seq"])+ thread = conn.execute(+ """SELECT thread_id, discussion_event_id+ FROM hosted_room_policy_threads+ WHERE room_id=? AND completed=0 AND latest_user_seq>?+ ORDER BY latest_user_seq, thread_id LIMIT 1""",+ (room_id, stopped_through_seq),+ ).fetchone()+ if thread is None:+ return PolicySnapshot(+ through_seq=through_seq,+ stopped_through_seq=stopped_through_seq,+ events=(),+ watermarks={},+ )+ active_rows = conn.execute(+ """SELECT event_json FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=?+ ORDER BY seq LIMIT ?""",+ (+ room_id,+ str(thread["discussion_event_id"]),+ MAX_ACTIVE_POLICY_EVENTS + 1,+ ),+ ).fetchall()+ if len(active_rows) > MAX_ACTIVE_POLICY_EVENTS:+ raise RuntimeError("active room policy projection exceeded its bound")+ transcript_events = self._transcript_events(+ conn,+ room_id=room_id,+ thread_id=str(thread["thread_id"]),+ )+ watermark_rows = conn.execute(+ """SELECT member_id, seen_through_seq+ FROM hosted_room_policy_watermarks+ WHERE room_id=? AND thread_id=?""",+ (room_id, str(thread["thread_id"])),+ ).fetchall()+ events_by_seq = {+ int(event["seq"]): event+ for event in (+ *transcript_events,+ *(json.loads(row["event_json"]) for row in active_rows),+ )+ }+ return PolicySnapshot(+ through_seq=through_seq,+ stopped_through_seq=stopped_through_seq,+ events=tuple(events_by_seq[seq] for seq in sorted(events_by_seq)),+ watermarks={+ (str(thread["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:+ """Return whether one exact driver outcome is already in the room log."""++ kind = f"turn.{status}"+ generation = execution_generation if status == "deferred" else 0+ with self._connect() as conn:+ if status == "deferred":+ row = conn.execute(+ """SELECT 1 FROM hosted_room_policy_publications+ WHERE room_id=? AND task_id=? AND kind=?+ AND execution_generation=?""",+ (room_id, task_id, kind, generation),+ ).fetchone()+ else:+ row = conn.execute(+ """SELECT 1 FROM hosted_room_policy_publications+ WHERE room_id=? AND task_id=? AND kind IN (+ 'turn.settled', 'turn.failed', 'turn.cancelled'+ )""",+ (room_id, task_id),+ ).fetchone()+ return row is not None++ def events_for_task(+ self,+ *,+ room_id: str,+ source_event_seq: int,+ ) -> list[dict[str, Any]]:+ """Load one bounded discussion projection for terminal reconstruction."""++ with self._connect() as conn:+ source = conn.execute(+ """SELECT discussion_event_id, thread_id+ FROM hosted_room_policy_events+ WHERE room_id=? AND seq=?""",+ (room_id, source_event_seq),+ ).fetchone()+ if source is None:+ return []+ active_rows = conn.execute(+ """SELECT event_json FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=?+ ORDER BY seq LIMIT ?""",+ (+ room_id,+ str(source["discussion_event_id"]),+ MAX_ACTIVE_POLICY_EVENTS + 1,+ ),+ ).fetchall()+ transcript_events = self._transcript_events(+ conn,+ room_id=room_id,+ thread_id=str(source["thread_id"]),+ )+ if len(active_rows) > MAX_ACTIVE_POLICY_EVENTS:+ raise RuntimeError("task policy projection exceeded its bound")+ events_by_seq = {+ int(event["seq"]): event+ for event in (+ *transcript_events,+ *(json.loads(row["event_json"]) for row in active_rows),+ )+ }+ return [events_by_seq[seq] for seq in sorted(events_by_seq)]++ def compact_completed(self, *, room_id: str) -> None:+ """Drop any completed projections left by an interrupted sync."""++ with self._connect() as conn:+ completed = conn.execute(+ """SELECT discussion_event_id FROM hosted_room_policy_threads+ WHERE room_id=? AND completed=1""",+ (room_id,),+ ).fetchall()+ for row in completed:+ conn.execute(+ """DELETE FROM hosted_room_policy_events+ WHERE room_id=? AND discussion_event_id=?""",+ (room_id, str(row["discussion_event_id"])),+ )+ conn.execute(+ """DELETE FROM hosted_room_policy_threads+ WHERE room_id=? AND completed=1""",+ (room_id,),+ )diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex ec8da694f1e..625bfea9dfc 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -81,6 +81,7 @@ _EVENT_KINDS_BY_ACTOR = {"gateway": frozenset({"member.unavailable","room.activity",+ "room.stop_requested","turn.deferred","turn.reassigned","turn.cancelled",@@ -118,6 +119,10 @@ class RoomConflictError(HostedRoomError):"""Raised when an idempotency key is reused for different room state."""+class RoomProbeUnavailableError(HostedRoomError):+ """Raised when a non-blocking ownership probe cannot read the room store."""++class EventConflictError(HostedRoomError):"""Raised when an event id is reused with different immutable content."""@@ -444,6 +449,27 @@ def _connect(db_path: Path | str) -> sqlite3.Connection:return conn+def _read_connection(db_path: Path | str) -> sqlite3.Connection:+ """Open the room store without steady-state journal or migration writes."""++ path = Path(db_path)+ if not path.is_file():+ initialized = _connect(path)+ initialized.close()+ conn = sqlite3.connect(path, timeout=10)+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA foreign_keys=ON")+ if _schema_is_current(conn):+ return conn+ conn.close()+ migrated = _connect(path)+ migrated.close()+ conn = sqlite3.connect(path, timeout=10)+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA foreign_keys=ON")+ return conn++@contextmanagerdef _transaction(db_path: Path | str, *, immediate: bool = False@@ -481,6 +507,16 @@ def _raise_room_not_found(conn: sqlite3.Connection, room_id: str) -> NoReturn:raise RoomNotFoundError("hosted room not found")+def _table_exists(conn: sqlite3.Connection, table: str) -> bool:+ return (+ conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",+ (table,),+ ).fetchone()+ is not None+ )++def _room_from_row(row: sqlite3.Row, *, idempotent: bool = False) -> dict[str, Any]:room = {"room_id": row["room_id"],@@ -609,10 +645,24 @@ def _prune_disbanded_rooms_locked(WHERE room_id IN ({placeholders}) AND disbanded_at IS NOT NULL""",room_ids,)- conn.execute(- f"DELETE FROM hosted_room_events WHERE room_id IN ({placeholders})",- room_ids,+ dependent_tables = (+ "hosted_room_policy_transcript_state",+ "hosted_room_policy_transcript",+ "hosted_room_policy_publications",+ "hosted_room_policy_watermarks",+ "hosted_room_policy_events",+ "hosted_room_policy_threads",+ "hosted_room_policy_cursors",+ "hosted_room_driver_tasks",+ "hosted_room_driver_leases",+ "hosted_room_events",)+ for table in dependent_tables:+ if _table_exists(conn, table):+ conn.execute(+ f"DELETE FROM {table} WHERE room_id IN ({placeholders})",+ room_ids,+ )conn.execute(f"DELETE FROM hosted_rooms WHERE room_id IN ({placeholders})",room_ids,@@ -823,7 +873,7 @@ def list_rooms(limit: int = MAX_ROOM_LIST_LIMIT,offset: int = 0,) -> list[dict[str, Any]]:- """Return one bounded page of rooms ordered by most recent change."""+ """Return one bounded read-only page ordered by most recent change."""if (isinstance(limit, bool)or not isinstance(limit, int)@@ -832,8 +882,8 @@ def list_rooms(raise HostedRoomError(f"limit must be between 1 and {MAX_ROOM_LIST_LIMIT}")if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0:raise HostedRoomError("offset must be a non-negative integer")- with _transaction(db_path, immediate=True) as conn:- _prune_disbanded_rooms_locked(conn, now=None)+ conn = _read_connection(db_path)+ try:rows = conn.execute("""SELECT room_id, name, members_json, authority_gateway_id,authority_epoch, next_seq, revision, created_at, updated_at,@@ -844,6 +894,8 @@ def list_rooms(LIMIT ? OFFSET ?""",(int(include_disbanded), limit, offset),).fetchall()+ finally:+ conn.close()return [_room_from_row(row) for row in rows]@@ -1002,6 +1054,47 @@ def append_event(return result+def probe_hosted_room(db_path: Path | str, *, room_id: Any) -> bool:+ """Check room ownership without creating or migrating the shared store.++ This runs on the synchronous prompt-admission path for older Desktop+ clients, so it fails quickly under contention instead of blocking the+ WebSocket reader for SQLite's normal ten-second timeout.+ """++ checked_room_id = _validate_identifier(+ room_id,+ label="room_id",+ max_chars=MAX_ROOM_ID_CHARS,+ )+ path = Path(db_path)+ if not path.is_file():+ return False+ try:+ conn = sqlite3.connect(path, timeout=0.05)+ try:+ table = conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type='table' "+ "AND name='hosted_rooms' LIMIT 1"+ ).fetchone()+ if table is None:+ return False+ return (+ conn.execute(+ "SELECT 1 FROM hosted_rooms WHERE room_id=? "+ "AND disbanded_at IS NULL LIMIT 1",+ (checked_room_id,),+ ).fetchone()+ is not None+ )+ finally:+ conn.close()+ except sqlite3.Error as exc:+ raise RoomProbeUnavailableError(+ "hosted room ownership is temporarily unavailable"+ ) from exc++def room_state(db_path: Path | str,*,@@ -1041,6 +1134,34 @@ def room_state(return state+def request_room_stop(+ db_path: Path | str,+ *,+ 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]+ return append_event(+ db_path,+ room_id=room_id,+ event_id=f"room-stop:{digest}",+ kind="room.stop_requested",+ actor={"kind": "gateway", "id": expected_gateway_id},+ payload={"cancel_id": cancel_id},+ authority_gateway_id=expected_gateway_id,+ authority_epoch=expected_epoch,+ )++def claim_authority(db_path: Path | str,*,diff --git a/gateway/run.py b/gateway/run.pyindex 7aa6cf7930a..23dadfe4308 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -13082,6 +13082,43 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewlogger.warning("Legacy session recovery on startup failed: %s", exc)return exact, fallback+ @staticmethod+ def _start_hosted_room_worker_sync():+ """Start the local Group Chat worker without importing the dashboard."""++ import tui_gateway.server # noqa: F401+ from tui_gateway import methods_groups++ service = methods_groups.get_hosted_room_service()+ if service is None:+ service = methods_groups.start_hosted_room_service()+ if service is None:+ raise RuntimeError("Group Chat worker has no bound session backend")+ status = service.runtime.status()+ if not status.get("running") or status.get("stopping"):+ raise RuntimeError("Group Chat worker did not start")+ return service++ async def _ensure_hosted_room_worker(self):+ return await asyncio.to_thread(self._start_hosted_room_worker_sync)++ async def _hosted_room_worker_watcher(self, interval: float = 1.0) -> None:+ """Keep the room worker alive for the messaging gateway lifetime."""++ while self._running:+ await self._ensure_hosted_room_worker()+ await asyncio.sleep(interval)++ async def _stop_hosted_room_worker(self, timeout: float = 5.0) -> bool:+ """Pause room execution durably without interrupting accepted turns."""++ from tui_gateway import methods_groups++ return await asyncio.to_thread(+ methods_groups.stop_hosted_room_service,+ timeout=timeout,+ )+def _start_loop_heartbeat_task(self) -> None:"""Start the loop-liveness heartbeat task (#66892), idempotent.@@ -13888,6 +13925,19 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._install_plugin_message_injector()self._update_runtime_status("running")+ try:+ await self._ensure_hosted_room_worker()+ except Exception:+ logger.error(+ "Group Chat worker failed to start; mutating Group Chat commands "+ "will fail closed until supervision recovers it",+ exc_info=True,+ )+ self._spawn_supervised(+ self._hosted_room_worker_watcher,+ "hosted_room_worker",+ )+self._start_loop_heartbeat_task()# Emit gateway:startup hook@@ -15744,6 +15794,22 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewself._clear_plugin_message_injector()self._draining = True+ stop_room_worker = getattr(self, "_stop_hosted_room_worker", None)+ if callable(stop_room_worker):+ try:+ stopped = await stop_room_worker(timeout=5.0)+ if not stopped:+ logger.warning(+ "Group Chat worker is still settling durable work; "+ "the next gateway start will recover it"+ )+ except Exception:+ logger.warning(+ "Group Chat worker could not stop cleanly; the next gateway "+ "start will recover durable work",+ exc_info=True,+ )+stop_watchdog = getattr(self, "_stop_systemd_watchdog", None)if callable(stop_watchdog):await stop_watchdog()diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex fab84d150a0..9dfc5ef6436 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -431,6 +431,31 @@ async def _lifespan(app: "FastAPI"):record_boot_fingerprint()+ # Hosted Bot rooms belong to the backend process, not to any connected+ # Desktop socket. Recovery may need a contended state.db migration, so keep+ # it off the lifespan's pre-yield path: Group Chat startup must degrade on+ # its own instead of preventing every dashboard/Desktop feature from booting.+ from tui_gateway import methods_groups as _hosted_groups+ import tui_gateway.server # noqa: F401++ hosted_room_start_cancel = threading.Event()++ def _start_hosted_rooms() -> None:+ try:+ _hosted_groups.start_hosted_room_service()+ except Exception:+ _log.exception("Hosted Group Chat recovery failed during backend startup")+ finally:+ if hosted_room_start_cancel.is_set():+ _hosted_groups.stop_hosted_room_service(timeout=1.0)++ hosted_room_start_thread = threading.Thread(+ target=_start_hosted_rooms,+ daemon=True,+ name="hosted-room-startup",+ )+ hosted_room_start_thread.start()+# Desktop-spawned backends (HERMES_DESKTOP=1) fire cron jobs themselves,# since the app has no gateway running the scheduler. Server `hermes# dashboard` is unaffected — it relies on its own gateway.@@ -473,6 +498,9 @@ async def _lifespan(app: "FastAPI"):try:yieldfinally:+ hosted_room_start_cancel.set()+ _hosted_groups.stop_hosted_room_service(timeout=5.0)+ hosted_room_start_thread.join(timeout=1.0)if cron_stop is not None:cron_stop.set()pty_reaper_task.cancel()diff --git a/tests/gateway/test_hosted_room_discussion.py b/tests/gateway/test_hosted_room_discussion.pynew file mode 100644index 00000000000..a653be1df0e--- /dev/null+++ b/tests/gateway/test_hosted_room_discussion.py@@ -0,0 +1,708 @@+"""Behavior tests for deterministic same-gateway Discussion policy."""++from __future__ import annotations++import time+from pathlib import Path++import pytest++from gateway import hosted_room_discussion as discussion+from gateway import hosted_room_driver as driver+from gateway import hosted_rooms+++ROOM_ID = "room-1"+GATEWAY_ID = "gateway-a"+LOCAL_PROFILES = ("research", "build", "review", "ops", "qa", "docs")+MEMBERS = [+ {+ "member_id": f"member-{profile}",+ "profile": profile,+ "handle": profile,+ "display_name": profile.title(),+ }+ for profile in LOCAL_PROFILES[:3]+]+++def room_db(tmp_path: Path) -> tuple[Path, dict]:+ db = tmp_path / "state.db"+ room = hosted_rooms.create_room(+ db,+ room_id=ROOM_ID,+ name="Release",+ members=MEMBERS,+ authority_gateway_id=GATEWAY_ID,+ now=1,+ )+ return db, room+++def _events(db: Path) -> list[dict]:+ return hosted_rooms.read_events(+ db,+ room_id=ROOM_ID,+ since_seq=0,+ limit=hosted_rooms.MAX_LOG_LIMIT,+ )["events"]+++def _append_user(+ db: Path,+ *,+ event_id: str,+ text: str,+ thread_id: str = "thread-1",+) -> dict:+ return hosted_rooms.append_event(+ db,+ room_id=ROOM_ID,+ event_id=event_id,+ kind="message.user",+ actor={"kind": "user", "id": "local-user"},+ authority_gateway_id=GATEWAY_ID,+ authority_epoch=1,+ payload={"text": text, "thread_id": thread_id},+ now=time.time(),+ )+++def _append_publication(+ db: Path,+ plan: discussion.PublicationPlan,+) -> list[dict]:+ return [+ hosted_rooms.append_event(+ db,+ **event.append_kwargs(ROOM_ID),+ now=time.time(),+ )+ for event in plan.events+ ]+++def _append_activity(+ db: Path,+ *,+ event_id: str,+ discussion_event_id: str,+ thread_id: str,+) -> dict:+ return hosted_rooms.append_event(+ db,+ room_id=ROOM_ID,+ event_id=event_id,+ kind="room.activity",+ actor={"kind": "gateway", "id": GATEWAY_ID},+ payload={+ "status": "settled",+ "reason_code": "silent_round",+ "thread_id": thread_id,+ "discussion_event_id": discussion_event_id,+ },+ authority_gateway_id=GATEWAY_ID,+ authority_epoch=1,+ )+++def _next_task(room: dict, db: Path) -> discussion.DiscussionTaskPlan:+ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "task", decision+ assert decision.task is not None+ return decision.task+++def _settle_next(+ room: dict,+ db: Path,+ *,+ text: str,+) -> discussion.DiscussionTaskPlan:+ task = _next_task(room, db)+ publication = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": text},+ local_profiles=LOCAL_PROFILES,+ )+ _append_publication(db, publication)+ return task+++def test_deferred_member_allows_next_mentioned_member_and_later_terminal_result(+ room_db,+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Report.")+ first = _next_task(room, db)+ deferred = discussion.plan_publication(+ room,+ _events(db),+ first,+ status="deferred",+ result={"reason": "member_unavailable"},+ execution_generation=1,+ local_profiles=LOCAL_PROFILES,+ )+ _append_publication(db, deferred)++ second = _next_task(room, db)+ assert second.member.member_id != first.member.member_id++ settled = discussion.plan_publication(+ room,+ _events(db),+ first,+ status="settled",+ result={"text": "Recovered on explicit retry."},+ local_profiles=LOCAL_PROFILES,+ )+ _append_publication(db, settled)+ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "task"+ assert decision.task is not None+ assert decision.task.member.member_id == second.member.member_id+++def test_distinct_threads_are_planned_fifo_without_skipping(room_db):+ db, room = room_db+ _append_user(db, event_id="user-1", text="First", thread_id="thread-1")+ _append_user(db, event_id="user-2", text="Second", thread_id="thread-2")++ first = _next_task(room, db)+ assert first.discussion_event_id == "user-1"+ _append_activity(+ db,+ event_id="activity-1",+ discussion_event_id="user-1",+ thread_id="thread-1",+ )+ second = _next_task(room, db)+ assert second.discussion_event_id == "user-2"+++def test_room_stop_fences_old_work_but_allows_a_later_message(room_db):+ db, room = room_db+ _append_user(db, event_id="user-1", text="First", thread_id="thread-1")+ stop = hosted_rooms.request_room_stop(+ db,+ room_id=ROOM_ID,+ cancel_id="user-stop-1",+ expected_gateway_id=str(room["authority_gateway_id"]),+ expected_epoch=int(room["authority_epoch"]),+ )+ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "idle"+ assert stop["kind"] == "room.stop_requested"++ _append_user(db, event_id="user-2", text="Continue", thread_id="thread-2")+ resumed = _next_task(room, db)+ assert resumed.discussion_event_id == "user-2"+++def test_deterministic_task_fits_existing_driver_and_reconstructs_after_restart(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ user = _append_user(db, event_id="user-1", text="Check the release.")++ first = _next_task(room, db)+ repeated = _next_task(room, db)+ assert first == repeated+ assert first.identity.thread_id == "thread-1"+ assert first.payload == {+ "target_profile": "research",+ "prompt": first.payload["prompt"],+ "source_event_seq": user["seq"],+ }+ assert set(first.payload) == {"target_profile", "prompt", "source_event_seq"}++ admitted = driver.admit_task(+ db,+ first.identity,+ payload=first.payload,+ clock=time.time,+ )+ stored = driver.get_task(db, first.identity)+ reconstructed = discussion.reconstruct_task_plan(+ room,+ _events(db),+ stored,+ local_profiles=LOCAL_PROFILES,+ )+ assert admitted["status"] == "queued"+ assert reconstructed == first++ reopened_events = _events(db)+ assert (+ discussion.reconstruct_task_plan(+ room,+ reopened_events,+ driver.get_task(db, first.identity),+ local_profiles=LOCAL_PROFILES,+ )+ == first+ )+++ ("text", "expected_profile"),+ [+ ("@build please inspect this", "build"),+ ("@all inspect this", "research"),+ ("@everyone inspect this", "research"),+ ("inspect this", "research"),+ ("@unknown inspect this", "research"),+ ],+)+def test_mentions_select_handles_or_everyone(+ room_db: tuple[Path, dict],+ text: str,+ expected_profile: str,+):+ db, room = room_db+ _append_user(db, event_id="user-1", text=text)++ assert _next_task(room, db).member.profile == expected_profile+++def test_member_mention_joins_the_next_round_not_the_current_round(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="@research lead this")++ first = _settle_next(room, db, text="@build can add the implementation detail.")+ second = _next_task(room, db)++ assert first.member.profile == "research"+ assert first.round_index == 0+ assert second.member.profile == "build"+ assert second.round_index == 1+ assert "@research lead this" in second.payload["prompt"]+ assert "@build can add the implementation detail." in second.payload["prompt"]+++def test_plain_member_reply_does_not_wake_another_bot_round(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="@research answer the user")+ _settle_next(room, db, text="The answer is ready for the user.")++ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )++ assert decision.status == "settled"+ assert decision.reason == "silent_round"++[email protected]("value", ["", "pass", "pass.", "(pass)", " ( PASS ). "])+def test_pass_detection(value: str):+ assert discussion.is_pass_text(value)+++def test_real_text_is_not_a_pass():+ assert not discussion.is_pass_text("I found the issue.")+++def test_full_pass_round_settles_without_member_messages(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Any concerns?")++ for _member in MEMBERS:+ _settle_next(room, db, text="(pass)")++ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "settled"+ assert decision.reason == "silent_round"+ assert [event["kind"] for event in _events(db)].count("message.member") == 0+++def test_failed_members_advance_the_round_as_silence(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Any concerns?")++ for expected in ("research", "build", "review"):+ task = _next_task(room, db)+ assert task.member.profile == expected+ publication = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="failed",+ result={"error": f"{expected} unavailable"},+ local_profiles=LOCAL_PROFILES,+ )+ assert publication.terminal_kind == "turn.failed"+ assert len(publication.events) == 1+ _append_publication(db, publication)++ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "settled"+ assert decision.reason == "silent_round"+++def test_publication_is_idempotent_and_changed_result_conflicts(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Report.")+ task = _next_task(room, db)+ publication = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": "Ready."},+ local_profiles=LOCAL_PROFILES,+ )++ first = _append_publication(db, publication)+ repeated = _append_publication(db, publication)+ assert [event["seq"] for event in first] == [event["seq"] for event in repeated]+ assert all(event["idempotent"] for event in repeated)++ changed = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": "Different."},+ local_profiles=LOCAL_PROFILES,+ )+ with pytest.raises(hosted_rooms.EventConflictError):+ _append_publication(db, changed)+++def test_partial_publication_replays_same_effects_before_policy_advances(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Report.")+ task = _next_task(room, db)+ publication = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": "Ready."},+ local_profiles=LOCAL_PROFILES,+ )++ message_effect = publication.events[0]+ hosted_rooms.append_event(+ db,+ **message_effect.append_kwargs(ROOM_ID),+ now=time.time(),+ )+ assert _next_task(room, db).identity == task.identity++ replayed = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": "Ready."},+ local_profiles=LOCAL_PROFILES,+ )+ _append_publication(db, replayed)+ assert _next_task(room, db).member.profile == "build"+++def test_watermark_excludes_a_members_old_input_and_own_reply(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Old request.")+ first = _settle_next(room, db, text="Old answer.")+ watermark = discussion.derive_member_watermarks(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )[("thread-1", first.member.member_id)]+ assert watermark == max(+ event["seq"]+ for event in _events(db)+ if event["kind"] == "message.member"+ and event["payload"]["task_id"] == first.identity.task_id+ )++ latest = _append_user(db, event_id="user-2", text="New request.")+ next_task = _next_task(room, db)+ assert next_task.member.profile == "research"+ assert next_task.payload["source_event_seq"] == latest["seq"]+ assert "New request." in next_task.payload["prompt"]+ assert "Old request." not in next_task.payload["prompt"]+ assert "Old answer." not in next_task.payload["prompt"]+++def test_newer_same_thread_user_event_cancels_a_late_result(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="First request.")+ stale = _next_task(room, db)+ latest = _append_user(db, event_id="user-2", text="Second request.")++ publication = discussion.plan_publication(+ room,+ _events(db),+ stale,+ status="settled",+ result={"text": "Late stale answer."},+ local_profiles=LOCAL_PROFILES,+ )+ assert publication.terminal_kind == "turn.cancelled"+ assert [event.kind for event in publication.events] == ["turn.cancelled"]+ assert publication.events[0].payload["reason"] == "superseded_by_newer_user_event"+ _append_publication(db, publication)++ current = _next_task(room, db)+ assert current.payload["source_event_seq"] == latest["seq"]+ assert "Second request." in current.payload["prompt"]+++def test_cross_thread_newer_user_does_not_discard_completed_old_reply(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="First request.", thread_id="thread-1")+ old = _next_task(room, db)+ _append_user(db, event_id="user-2", text="Other topic.", thread_id="thread-2")++ publication = discussion.plan_publication(+ room,+ _events(db),+ old,+ status="settled",+ result={"text": "Completed first topic."},+ local_profiles=LOCAL_PROFILES,+ )+ assert [event.kind for event in publication.events] == [+ "message.member",+ "turn.settled",+ ]+++def test_oversized_member_reply_is_truncated_and_next_turn_stays_serviceable(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(+ db,+ event_id="user-large",+ text="u" * discussion.MAX_USER_TEXT_BYTES,+ )+ first = _next_task(room, db)+ publication = discussion.plan_publication(+ room,+ _events(db),+ first,+ status="settled",+ result={"text": "é" * (discussion.MAX_MEMBER_TEXT_BYTES + 100)},+ local_profiles=LOCAL_PROFILES,+ )++ member_event = next(event for event in publication.events if event.kind == "message.member")+ member_text = member_event.payload["text"]+ assert len(member_text.encode("utf-8")) <= discussion.MAX_MEMBER_TEXT_BYTES+ assert member_text.endswith("share the full result as a file.]")+ _append_publication(db, publication)++ followup = _next_task(room, db)+ assert len(followup.payload["prompt"].encode("utf-8")) <= driver.MAX_PROMPT_BYTES+ assert "Earlier content omitted" in followup.payload["prompt"]+++def test_three_round_bound(room_db: tuple[Path, dict]):+ db, room = room_db+ room["members"] = MEMBERS[:2]+ _append_user(db, event_id="user-1", text="Discuss.")++ for index in range(6):+ task = _next_task(room, db)+ peer = "build" if task.member.profile == "research" else "research"+ publication = discussion.plan_publication(+ room,+ _events(db),+ task,+ status="settled",+ result={"text": f"Reply {index}. @{peer}"},+ local_profiles=LOCAL_PROFILES,+ )+ _append_publication(db, publication)++ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "bounded"+ assert decision.reason == "max_rounds"+++def test_ten_message_bound(tmp_path: Path):+ db = tmp_path / "state.db"+ members = [+ {+ "member_id": f"member-{profile}",+ "profile": profile,+ "handle": profile,+ }+ for profile in LOCAL_PROFILES+ ]+ room = hosted_rooms.create_room(+ db,+ room_id=ROOM_ID,+ name="Large",+ members=members,+ authority_gateway_id=GATEWAY_ID,+ now=1,+ )+ _append_user(db, event_id="user-1", text="Discuss.")++ for index in range(discussion.MAX_DISCUSSION_MESSAGES):+ _settle_next(room, db, text=f"Reply {index}. @everyone")++ decision = discussion.plan_next_task(+ room,+ _events(db),+ local_profiles=LOCAL_PROFILES,+ )+ assert decision.status == "bounded"+ assert decision.reason == "max_messages"+++def test_prompt_delta_is_bounded_to_24_message_lines(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ for index in range(30):+ _append_user(+ db,+ event_id=f"user-{index}",+ text=f"Message {index}.",+ )++ task = _next_task(room, db)+ assert task.payload["prompt"].count("User (user):") == 24+ assert "Message 5." not in task.payload["prompt"]+ assert "Message 6." in task.payload["prompt"]+ assert "Message 29." in task.payload["prompt"]+++def test_attachment_payload_is_rejected_by_local_text_only_boundary():+ with pytest.raises(discussion.DiscussionValidationError, match="unknown fields"):+ discussion.validate_user_payload({+ "text": "Review.",+ "thread_id": "thread-1",+ "attachments": [{"name": "notes.txt"}],+ })+++ ("members", "match"),+ [+ (MEMBERS[:1], "between 2 and 6"),+ (MEMBERS + MEMBERS + MEMBERS[:1], "between 2 and 6"),+ (+ [MEMBERS[0], {**MEMBERS[1], "profile": "research"}],+ "profiles must be unique",+ ),+ ([MEMBERS[0], {**MEMBERS[1], "handle": "RESEARCH"}], "handles must be unique"),+ (+ [MEMBERS[0], {**MEMBERS[1], "member_id": "MEMBER-RESEARCH"}],+ "ids must be unique",+ ),+ ([MEMBERS[0], {**MEMBERS[1], "route": {"mode": "ssh"}}], "cross-gateway"),+ ([MEMBERS[0], {**MEMBERS[1], "connectionId": "remote"}], "cross-gateway"),+ ([MEMBERS[0], {**MEMBERS[1], "profile": "missing"}], "not local"),+ ],+)+def test_malformed_or_remote_roster_is_rejected(members: list[dict], match: str):+ with pytest.raises(discussion.DiscussionValidationError, match=match):+ discussion.validate_roster(members, local_profiles=LOCAL_PROFILES)+++ "payload",+ [+ {"text": "hello"},+ {"text": "hello", "thread_id": "thread-1", "images": []},+ {"text": "", "thread_id": "thread-1"},+ {"text": "hello", "thread_id": "../escape"},+ {"text": ["hello"], "thread_id": "thread-1"},+ ],+)+def test_user_payload_is_exact_and_text_only(payload: dict):+ with pytest.raises(discussion.DiscussionValidationError):+ discussion.validate_user_payload(payload)+++def test_malformed_log_and_task_reconstruction_fail_closed(+ room_db: tuple[Path, dict],+):+ db, room = room_db+ _append_user(db, event_id="user-1", text="Report.")+ _append_user(db, event_id="user-2", text="Report again.")+ task = _next_task(room, db)+ events = _events(db)++ with pytest.raises(discussion.DiscussionValidationError, match="sequence order"):+ discussion.plan_next_task(+ room,+ list(reversed(events)),+ local_profiles=LOCAL_PROFILES,+ )++ malformed = {+ "identity": driver.TaskIdentity(+ room_id=task.identity.room_id,+ task_id="dtask:wrong",+ thread_id=task.identity.thread_id,+ turn_id=task.identity.turn_id,+ ),+ "payload": dict(task.payload),+ }+ with pytest.raises(+ discussion.DiscussionReconstructionError,+ match="deterministic reconstruction",+ ):+ discussion.reconstruct_task_plan(+ room,+ events,+ malformed,+ local_profiles=LOCAL_PROFILES,+ )diff --git a/tests/gateway/test_hosted_room_driver.py b/tests/gateway/test_hosted_room_driver.pynew file mode 100644index 00000000000..78f6fe9c9d8--- /dev/null+++ b/tests/gateway/test_hosted_room_driver.py@@ -0,0 +1,1110 @@+"""Behavior tests for the hosted-room driver state machine."""++from __future__ import annotations++import sqlite3+from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor++import pytest++from gateway import hosted_rooms as rooms+from gateway import hosted_room_driver as driver+++class FakeClock:+ def __init__(self, value: float = 100.0):+ self.value = value++ def __call__(self) -> float:+ return self.value++ def advance(self, seconds: float) -> None:+ self.value += seconds+++def _identity(task_id: str = "task-1", *, turn_id: str = "turn-1"):+ return driver.TaskIdentity(+ room_id="room-1",+ task_id=task_id,+ thread_id="thread-1",+ turn_id=turn_id,+ )+++def _payload(+ *,+ target_profile: str = "ops",+ prompt: str = "Inspect the release candidate.",+ source_event_seq: int = 1,+):+ return {+ "target_profile": target_profile,+ "prompt": prompt,+ "source_event_seq": source_event_seq,+ }+++def db(tmp_path):+ path = tmp_path / "state.db"+ rooms.create_room(+ path,+ room_id="room-1",+ name="Release room",+ members=[{"profile": "ops", "handle": "ops"}],+ authority_gateway_id="gateway-a",+ now=90,+ )+ return path+++def _lease(+ db,+ clock,+ *,+ gateway="gateway-a",+ authority_epoch=1,+ process="process-a",+ ttl=30,+):+ return driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id=gateway,+ authority_epoch=authority_epoch,+ process_generation=process,+ ttl_seconds=ttl,+ clock=clock,+ )+++def _admit(db, identity, clock, *, payload=None):+ return driver.admit_task(+ db,+ identity,+ payload=_payload() if payload is None else payload,+ clock=clock,+ )+++def _open_driver_schema(path: str) -> int:+ return len(driver.list_tasks(path, room_id="room-1"))+++def test_two_contenders_have_one_winner(db):+ clock = FakeClock()++ def contend(process):+ try:+ return _lease(db, clock, process=process)+ except driver.LeaseHeldError:+ return None++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(contend, ["process-a", "process-b"]))++ winners = [result for result in results if result is not None]+ assert len(winners) == 1+ assert winners[0].lease_generation == 1+++def test_expiry_allows_reclaim_and_fences_stale_renew_and_release(db):+ clock = FakeClock()+ first = _lease(db, clock, ttl=5)++ clock.advance(5)+ second = _lease(db, clock, process="process-b")++ assert second.reclaimed is True+ assert second.lease_generation == first.lease_generation + 1+ with pytest.raises(driver.StaleLeaseError):+ driver.renew_lease(db, first, ttl_seconds=30, clock=clock)+ with pytest.raises(driver.StaleLeaseError):+ driver.release_lease(db, first, clock=clock)+++def test_nonexistent_and_disbanded_rooms_cannot_lease_or_admit(db):+ clock = FakeClock()+ missing = driver.TaskIdentity("missing-room", "task", "thread", "turn")++ with pytest.raises(driver.RoomUnavailableError, match="does not exist"):+ driver.acquire_lease(+ db,+ room_id="missing-room",+ gateway_id="gateway-a",+ authority_epoch=1,+ process_generation="process-a",+ ttl_seconds=30,+ clock=clock,+ )+ with pytest.raises(driver.RoomUnavailableError, match="does not exist"):+ _admit(db, missing, clock)++ rooms.disband_room(+ db,+ room_id="room-1",+ expected_gateway_id="gateway-a",+ expected_epoch=1,+ now=clock(),+ )+ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ _lease(db, clock)+ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ _admit(db, _identity(), clock)+++ ("gateway", "authority_epoch"),+ [("gateway-b", 1), ("gateway-a", 2)],+)+def test_acquire_requires_current_room_authority(db, gateway, authority_epoch):+ with pytest.raises(driver.StaleLeaseError, match="authority changed"):+ _lease(+ db,+ FakeClock(),+ gateway=gateway,+ authority_epoch=authority_epoch,+ )+++def test_same_process_acquire_and_release_are_idempotent(db):+ clock = FakeClock()+ first = _lease(db, clock)+ repeated = _lease(db, clock)++ assert repeated.lease_generation == first.lease_generation+ released = driver.release_lease(db, repeated, clock=clock)+ released_again = driver.release_lease(db, repeated, clock=clock)++ assert released["idempotent"] is False+ assert released_again["idempotent"] is True+++def test_renew_extends_only_the_current_lease_generation(db):+ clock = FakeClock()+ lease = _lease(db, clock, ttl=5)++ clock.advance(2)+ renewed = driver.renew_lease(db, lease, ttl_seconds=20, clock=clock)++ assert renewed.lease_generation == lease.lease_generation+ assert renewed.expires_at == 122+++def test_authority_transfer_fences_lease_and_late_settlement(db):+ clock = FakeClock()+ identity = _identity()+ queued = _identity("task-2", turn_id="turn-2")+ old_lease = _lease(db, clock)+ _admit(db, identity, clock)+ _admit(db, queued, clock)+ old_attempt = driver.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )++ rooms.claim_authority(+ db,+ room_id="room-1",+ expected_gateway_id="gateway-a",+ expected_epoch=1,+ new_gateway_id="gateway-b",+ event_id="claim-gateway-b",+ now=clock(),+ )++ with pytest.raises(driver.StaleLeaseError, match="authority changed"):+ driver.renew_lease(db, old_lease, ttl_seconds=30, clock=clock)+ with pytest.raises(driver.StaleLeaseError, match="authority changed"):+ driver.start_task(+ db,+ queued,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ with pytest.raises(driver.StaleLeaseError, match="authority changed"):+ driver.recover_room(db, old_lease, clock=clock)+ with pytest.raises(driver.StaleLeaseError, match="authority changed"):+ driver.settle_task(+ db,+ old_attempt,+ settlement_id="late-settlement",+ status="settled",+ result={"text": "late"},+ clock=clock,+ )++ new_lease = _lease(+ db,+ clock,+ gateway="gateway-b",+ authority_epoch=2,+ process="process-b",+ )+ recovery = driver.recover_room(db, new_lease, clock=clock)+ assert new_lease.lease_generation == old_lease.lease_generation + 1+ assert recovery["indeterminate"] == [identity]+ assert recovery["queued"] == [queued]+++def test_room_disband_fences_active_lease_operations(db):+ clock = FakeClock()+ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)+ rooms.disband_room(+ db,+ room_id="room-1",+ expected_gateway_id="gateway-a",+ expected_epoch=1,+ now=clock(),+ )++ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ driver.renew_lease(db, lease, ttl_seconds=30, clock=clock)+ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ driver.recover_room(db, lease, clock=clock)+ with pytest.raises(driver.RoomUnavailableError, match="disbanded"):+ driver.release_lease(db, lease, clock=clock)+++def test_task_admission_is_idempotent_and_identity_conflicts_fail(db):+ clock = FakeClock()+ identity = _identity()++ first = _admit(db, identity, clock)+ repeated = _admit(db, identity, clock)++ assert first["status"] == "queued"+ assert repeated["idempotent"] is True++ with pytest.raises(driver.TaskConflictError):+ driver.admit_task(+ db,+ driver.TaskIdentity(+ room_id="room-1",+ task_id="task-1",+ thread_id="thread-other",+ turn_id="turn-other",+ ),+ payload=_payload(),+ clock=clock,+ )++ with pytest.raises(driver.TaskConflictError, match="different payload"):+ _admit(+ db,+ identity,+ clock,+ payload=_payload(prompt="A different immutable prompt."),+ )+ with pytest.raises(driver.TaskConflictError):+ driver.admit_task(+ db,+ driver.TaskIdentity(+ room_id="room-1",+ task_id="task-other",+ thread_id="thread-1",+ turn_id="turn-1",+ ),+ payload=_payload(),+ clock=clock,+ )+++def test_concurrent_task_start_has_one_winner(db):+ clock = FakeClock()+ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)++ def start(_):+ try:+ return driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ except driver.InvalidTaskTransitionError:+ return None++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(start, range(2)))++ winners = [result for result in results if result is not None]+ assert len(winners) == 1+ assert winners[0].execution_generation == 1+++def test_stale_lease_cannot_start_or_commit_task(db):+ clock = FakeClock()+ identity = _identity()+ first = _lease(db, clock, ttl=5)+ _admit(db, identity, clock)+ attempt = driver.start_task(+ db,+ identity,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )++ clock.advance(5)+ second = _lease(db, clock, process="process-b")+ driver.recover_room(db, second, clock=clock)++ with pytest.raises(driver.StaleLeaseError):+ driver.settle_task(+ db,+ attempt,+ settlement_id="settlement-old",+ status="settled",+ result={"text": "late"},+ clock=clock,+ )+ assert driver.get_task(db, identity)["status"] == "indeterminate"++[email protected]("status", ["settled", "failed"])+def test_terminal_settlement_is_idempotent(db, status):+ clock = FakeClock()+ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)+ attempt = driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )++ first = driver.settle_task(+ db,+ attempt,+ settlement_id="settlement-1",+ status=status,+ result={"text": "done"},+ clock=clock,+ )+ repeated = driver.settle_task(+ db,+ attempt,+ settlement_id="settlement-1",+ status=status,+ result={"text": "done"},+ clock=clock,+ )++ assert first["status"] == status+ assert repeated["idempotent"] is True+ with pytest.raises(driver.TaskConflictError):+ driver.settle_task(+ db,+ attempt,+ settlement_id="settlement-2",+ status=status,+ result={"text": "changed"},+ clock=clock,+ )+++def test_cancellation_fences_late_success(db):+ clock = FakeClock()+ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)+ attempt = driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )++ stopping = driver.begin_task_cancel(+ db,+ identity,+ cancel_id="cancel-1",+ expected_cancel_generation=0,+ clock=clock,+ )+ cancelled = driver.complete_task_cancel(+ db,+ identity,+ cancel_id="cancel-1",+ expected_cancel_generation=1,+ clock=clock,+ )+ repeated = driver.complete_task_cancel(+ db,+ identity,+ cancel_id="cancel-1",+ expected_cancel_generation=1,+ clock=clock,+ )++ assert stopping["status"] == "stopping"+ assert cancelled["status"] == "cancelled"+ assert cancelled["cancel_generation"] == 1+ assert repeated["idempotent"] is True+ with pytest.raises(driver.StaleTaskError):+ driver.settle_task(+ db,+ attempt,+ settlement_id="late-success",+ status="settled",+ result={"text": "too late"},+ clock=clock,+ )+++def test_release_fails_closed_while_its_task_is_running(db):+ clock = FakeClock()+ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)+ driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )++ with pytest.raises(+ driver.InvalidTaskTransitionError,+ match="tasks are running",+ ):+ driver.release_lease(db, lease, clock=clock)+ assert driver.get_task(db, identity)["status"] == "running"++ driver.begin_task_cancel(+ db,+ identity,+ cancel_id="cancel-before-release",+ expected_cancel_generation=0,+ clock=clock,+ )+ driver.complete_task_cancel(+ db,+ identity,+ cancel_id="cancel-before-release",+ expected_cancel_generation=1,+ clock=clock,+ )+ assert driver.release_lease(db, lease, clock=clock)["idempotent"] is False+++def test_restart_recovery_never_requeues_indeterminate_work(db):+ clock = FakeClock()+ running = _identity()+ queued = _identity("task-2", turn_id="turn-2")+ first = _lease(db, clock, ttl=5)+ _admit(db, running, clock)+ _admit(db, queued, clock)+ driver.start_task(+ db,+ running,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )++ with pytest.raises(driver.LeaseHeldError):+ _lease(db, clock, gateway="gateway-a", process="new-process")++ clock.advance(5)+ recovered_lease = _lease(+ db,+ clock,+ gateway="gateway-a",+ process="new-process",+ )+ recovery = driver.recover_room(db, recovered_lease, clock=clock)+ repeated = driver.recover_room(db, recovered_lease, clock=clock)++ assert recovery == {"queued": [queued], "indeterminate": [running]}+ assert repeated == recovery+ with pytest.raises(driver.InvalidTaskTransitionError):+ driver.start_task(+ db,+ running,+ recovered_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ assert [task["status"] for task in driver.list_tasks(db, room_id="room-1")] == [+ "indeterminate",+ "queued",+ ]+++def test_recovery_is_required_before_starting_later_work(db):+ clock = FakeClock()+ running = _identity()+ queued = _identity("task-2", turn_id="turn-2")+ first = _lease(db, clock, ttl=5)+ _admit(db, running, clock, payload=_payload(source_event_seq=1))+ _admit(db, queued, clock, payload=_payload(source_event_seq=2))+ driver.start_task(+ db,+ running,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )+ clock.advance(5)+ recovered = _lease(db, clock, process="new-process")++ with pytest.raises(+ driver.InvalidTaskTransitionError,+ match="recovery must resolve",+ ):+ driver.start_task(+ db,+ queued,+ recovered,+ expected_cancel_generation=0,+ clock=clock,+ )+++def test_current_lease_can_commit_verified_indeterminate_receipt(db):+ clock = FakeClock()+ running = _identity()+ queued = _identity("task-2", turn_id="turn-2")+ first = _lease(db, clock, ttl=5)+ _admit(db, running, clock, payload=_payload(source_event_seq=1))+ _admit(db, queued, clock, payload=_payload(source_event_seq=2))+ attempt = driver.start_task(+ db,+ running,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )+ clock.advance(5)+ recovered = _lease(db, clock, process="new-process")+ driver.recover_room(db, recovered, clock=clock)++ settled = driver.resolve_indeterminate_task(+ db,+ running,+ recovered,+ expected_execution_generation=attempt.execution_generation,+ expected_cancel_generation=attempt.cancel_generation,+ settlement_id="recovered-receipt",+ status="settled",+ result={"text": "recovered"},+ clock=clock,+ )+ next_attempt = driver.start_task(+ db,+ queued,+ recovered,+ expected_cancel_generation=0,+ clock=clock,+ )++ assert settled["status"] == "settled"+ assert next_attempt.execution_generation == 1+++def test_indeterminate_retry_is_explicit_and_advances_execution_generation(db):+ clock = FakeClock()+ identity = _identity()+ first = _lease(db, clock, ttl=5)+ _admit(db, identity, clock)+ original = driver.start_task(+ db,+ identity,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )+ clock.advance(5)+ recovered = _lease(db, clock, process="new-process")+ driver.recover_room(db, recovered, clock=clock)++ requeued = driver.requeue_indeterminate_task(+ db,+ identity,+ recovered,+ expected_execution_generation=original.execution_generation,+ expected_cancel_generation=original.cancel_generation,+ clock=clock,+ )+ retried = driver.start_task(+ db,+ identity,+ recovered,+ expected_cancel_generation=0,+ clock=clock,+ )++ assert requeued["status"] == "queued"+ assert retried.execution_generation == original.execution_generation + 1+++def test_indeterminate_task_can_be_deferred_retried_and_cancelled(db):+ clock = FakeClock()+ identity = _identity()+ first = _lease(db, clock, ttl=5)+ _admit(db, identity, clock)+ original = driver.start_task(+ db,+ identity,+ first,+ expected_cancel_generation=0,+ clock=clock,+ )+ clock.advance(5)+ recovered = _lease(db, clock, process="new-process", ttl=5)+ driver.recover_room(db, recovered, clock=clock)++ deferred = driver.defer_indeterminate_task(+ db,+ identity,+ recovered,+ expected_execution_generation=original.execution_generation,+ expected_cancel_generation=original.cancel_generation,+ reason="member_unavailable",+ clock=clock,+ )+ repeated = driver.defer_indeterminate_task(+ db,+ identity,+ recovered,+ expected_execution_generation=original.execution_generation,+ expected_cancel_generation=original.cancel_generation,+ reason="member_unavailable",+ clock=clock,+ )+ requeued = driver.requeue_deferred_task(+ db,+ identity,+ recovered,+ expected_execution_generation=original.execution_generation,+ expected_cancel_generation=original.cancel_generation,+ clock=clock,+ )+ retried = driver.start_task(+ db,+ identity,+ recovered,+ expected_cancel_generation=0,+ clock=clock,+ )++ assert deferred["status"] == "deferred"+ assert deferred["result"] == {+ "reason": "member_unavailable",+ "retryable": True,+ }+ assert repeated["idempotent"] is True+ assert requeued["status"] == "queued"+ assert retried.execution_generation == original.execution_generation + 1++ clock.advance(5)+ next_lease = _lease(db, clock, process="third-process")+ driver.recover_room(db, next_lease, clock=clock)+ driver.defer_indeterminate_task(+ db,+ identity,+ next_lease,+ expected_execution_generation=retried.execution_generation,+ expected_cancel_generation=retried.cancel_generation,+ reason="member_unavailable",+ clock=clock,+ )+ cancelled = driver.cancel_task(+ db,+ identity,+ cancel_id="cancel-deferred",+ expected_cancel_generation=0,+ clock=clock,+ )+ assert cancelled["status"] == "cancelled"+++def test_state_survives_sqlite_reopen_and_concurrent_duplicate_admission(db):+ clock = FakeClock()+ identity = _identity()++ def admit(_):+ return _admit(db, identity, clock)++ with ThreadPoolExecutor(max_workers=8) as pool:+ results = list(pool.map(admit, range(8)))++ assert sum(not result["idempotent"] for result in results) == 1+ with sqlite3.connect(db) as conn:+ count = conn.execute(+ "SELECT COUNT(*) FROM hosted_room_driver_tasks"+ ).fetchone()[0]+ assert count == 1+ reopened = driver.get_task(db, identity)+ listed = driver.list_tasks(db, room_id="room-1")+ assert reopened["identity"] == identity+ assert reopened["payload"] == _payload()+ assert listed[0]["payload"] == _payload()+++def test_prune_removes_only_old_published_terminal_tasks(db):+ clock = FakeClock()+ lease = _lease(db, clock)+ published = _identity("task-published", turn_id="turn-published")+ unpublished = _identity("task-unpublished", turn_id="turn-unpublished")+ for identity in (published, unpublished):+ _admit(db, identity, clock)+ attempt = driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ driver.settle_task(+ db,+ attempt,+ settlement_id=f"result:{identity.task_id}",+ status="settled",+ result={"text": "done"},+ clock=clock,+ )++ with sqlite3.connect(db) as conn:+ conn.execute(+ """CREATE TABLE hosted_room_policy_publications (+ room_id TEXT NOT NULL,+ task_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ execution_generation INTEGER NOT NULL DEFAULT 0,+ seq INTEGER NOT NULL,+ PRIMARY KEY(room_id, task_id, kind, execution_generation)+ )"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_publications+ VALUES ('room-1', 'task-published', 'turn.settled', 0, 3)"""+ )++ clock.advance(driver.TERMINAL_TASK_RETENTION_SECONDS + 1)+ assert (+ driver.prune_published_terminal_tasks(+ db,+ room_id="room-1",+ clock=clock,+ )+ == 1+ )+ assert [+ task["identity"].task_id for task in driver.list_tasks(db, room_id="room-1")+ ] == ["task-unpublished"]+++def test_unpublished_legacy_driver_schema_fails_closed(db):+ conn = sqlite3.connect(db)+ try:+ conn.execute("DROP TABLE IF EXISTS hosted_room_driver_tasks")+ conn.execute("DROP TABLE IF EXISTS hosted_room_driver_leases")+ conn.execute(+ """CREATE TABLE hosted_room_driver_leases (+ room_id TEXT PRIMARY KEY,+ gateway_id TEXT NOT NULL,+ process_generation TEXT NOT NULL,+ lease_generation INTEGER NOT NULL,+ expires_at REAL NOT NULL,+ acquired_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ released_at REAL+ )"""+ )+ conn.execute(+ """CREATE TABLE hosted_room_driver_tasks (+ room_id TEXT NOT NULL,+ task_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ turn_id TEXT NOT NULL,+ status TEXT NOT NULL,+ execution_generation INTEGER NOT NULL,+ cancel_generation INTEGER NOT NULL,+ run_gateway_id TEXT,+ run_process_generation TEXT,+ run_lease_generation INTEGER,+ cancel_id TEXT,+ settlement_id TEXT,+ settlement_status TEXT,+ result_json TEXT,+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ started_at REAL,+ terminal_at REAL,+ indeterminate_at REAL,+ PRIMARY KEY (room_id, task_id),+ UNIQUE (room_id, thread_id, turn_id)+ )"""+ )+ conn.execute(+ """INSERT INTO hosted_room_driver_leases+ VALUES ('room-1', 'gateway-a', 'old-process', 1,+ 200, 100, 100, NULL)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_driver_tasks+ (room_id, task_id, thread_id, turn_id, status,+ execution_generation, cancel_generation,+ run_gateway_id, run_process_generation, run_lease_generation,+ created_at, updated_at, started_at)+ VALUES ('room-1', 'task-1', 'thread-1', 'turn-1', 'running',+ 1, 0, 'gateway-a', 'old-process', 1, 100, 100, 100)"""+ )+ conn.commit()+ finally:+ conn.close()++ with pytest.raises(driver.DriverStateError, match="unsupported unpublished"):+ driver.get_task(db, _identity())+++def test_pre_stopping_schema_is_migrated_without_losing_tasks(db):+ clock = FakeClock()+ identity = _identity()+ _admit(db, identity, clock)++ with sqlite3.connect(db) as conn:+ current_sql = conn.execute(+ "SELECT sql FROM sqlite_master WHERE name='hosted_room_driver_tasks'"+ ).fetchone()[0]+ old_sql = current_sql.replace(", 'stopping'", "")+ conn.execute("DROP INDEX idx_hosted_room_driver_tasks_status")+ conn.execute(+ "ALTER TABLE hosted_room_driver_tasks RENAME TO hosted_room_driver_tasks_current"+ )+ conn.execute(old_sql)+ columns = ", ".join(driver._TASK_COLUMN_ORDER)+ conn.execute(+ f"""INSERT INTO hosted_room_driver_tasks ({columns})+ SELECT {columns} FROM hosted_room_driver_tasks_current"""+ )+ conn.execute("DROP TABLE hosted_room_driver_tasks_current")+ conn.execute(+ """CREATE INDEX idx_hosted_room_driver_tasks_status+ ON hosted_room_driver_tasks(+ room_id, status, source_event_seq, created_at, task_id+ )"""+ )++ assert driver.get_task(db, identity)["status"] == "queued"+ lease = _lease(db, clock)+ attempt = driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ stopping = driver.begin_task_cancel(+ db,+ identity,+ cancel_id="cancel-after-upgrade",+ expected_cancel_generation=attempt.cancel_generation,+ clock=clock,+ )++ assert stopping["status"] == "stopping"+ with sqlite3.connect(db) as conn:+ table_sql = conn.execute(+ "SELECT sql FROM sqlite_master WHERE name='hosted_room_driver_tasks'"+ ).fetchone()[0]+ assert "'stopping'" in table_sql+++def test_pre_deferred_schema_is_migrated_without_losing_tasks(db):+ clock = FakeClock()+ identity = _identity()+ _admit(db, identity, clock)++ with sqlite3.connect(db) as conn:+ current_sql = conn.execute(+ "SELECT sql FROM sqlite_master WHERE name='hosted_room_driver_tasks'"+ ).fetchone()[0]+ old_sql = current_sql.replace(", 'deferred'", "")+ conn.execute("DROP INDEX idx_hosted_room_driver_tasks_status")+ conn.execute(+ "ALTER TABLE hosted_room_driver_tasks RENAME TO hosted_room_driver_tasks_current"+ )+ conn.execute(old_sql)+ columns = ", ".join(driver._TASK_COLUMN_ORDER)+ conn.execute(+ f"""INSERT INTO hosted_room_driver_tasks ({columns})+ SELECT {columns} FROM hosted_room_driver_tasks_current"""+ )+ conn.execute("DROP TABLE hosted_room_driver_tasks_current")+ conn.execute(+ """CREATE INDEX idx_hosted_room_driver_tasks_status+ ON hosted_room_driver_tasks(+ room_id, status, source_event_seq, created_at, task_id+ )"""+ )++ assert driver.get_task(db, identity)["status"] == "queued"+ with sqlite3.connect(db) as conn:+ table_sql = conn.execute(+ "SELECT sql FROM sqlite_master WHERE name='hosted_room_driver_tasks'"+ ).fetchone()[0]+ assert "'deferred'" in table_sql+++def test_first_schema_creation_is_safe_across_processes(db):+ with sqlite3.connect(db) as conn:+ conn.execute("DROP TABLE IF EXISTS hosted_room_driver_tasks")+ conn.execute("DROP TABLE IF EXISTS hosted_room_driver_leases")+ conn.commit()++ with ProcessPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(_open_driver_schema, [str(db)] * 4))++ assert results == [0, 0, 0, 0]+++def test_tasks_follow_source_event_order_not_admission_time(db):+ clock = FakeClock()+ later = _identity("task-2", turn_id="turn-2")+ earlier = _identity("task-1", turn_id="turn-1")+ _admit(db, later, clock, payload=_payload(source_event_seq=2))+ _admit(db, earlier, clock, payload=_payload(source_event_seq=1))+ lease = _lease(db, clock)++ assert [task["identity"] for task in driver.list_tasks(db, room_id="room-1")] == [+ earlier,+ later,+ ]+ with pytest.raises(driver.InvalidTaskTransitionError, match="event order"):+ driver.start_task(+ db,+ later,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ assert (+ driver.start_task(+ db,+ earlier,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ ).identity+ == earlier+ )+++def test_payload_digest_is_verified_on_read(db):+ identity = _identity()+ _admit(db, identity, FakeClock())+ with sqlite3.connect(db) as conn:+ conn.execute(+ """UPDATE hosted_room_driver_tasks+ SET payload_json=REPLACE(payload_json, 'Inspect', 'Replace')+ WHERE room_id=? AND task_id=?""",+ (identity.room_id, identity.task_id),+ )+ conn.commit()++ with pytest.raises(driver.TaskConflictError, match="integrity"):+ driver.get_task(db, identity)+++ ("payload", "match"),+ [+ ({"target_profile": "ops", "prompt": "hello"}, "missing payload fields"),+ (+ {**_payload(), "unexpected": True},+ "unknown payload fields",+ ),+ (_payload(target_profile="bad profile"), "invalid target_profile"),+ (_payload(prompt=" "), "prompt must not be empty"),+ (_payload(prompt="x" * (driver.MAX_PROMPT_BYTES + 1)), "prompt is too large"),+ (_payload(source_event_seq=0), "source_event_seq"),+ (_payload(source_event_seq=True), "source_event_seq"),+ ],+)+def test_invalid_task_payload_is_rejected(db, payload, match):+ with pytest.raises(driver.DriverValidationError, match=match):+ _admit(db, _identity(), FakeClock(), payload=payload)+++ ("factory", "match"),+ [+ (+ lambda: driver.TaskIdentity("bad room", "task", "thread", "turn"),+ "invalid room_id",+ ),+ (+ lambda: driver.TaskIdentity("room", "", "thread", "turn"),+ "invalid task_id",+ ),+ ],+)+def test_invalid_task_identity_is_rejected(factory, match):+ with pytest.raises(driver.DriverValidationError, match=match):+ factory()+++def test_invalid_lease_clock_ttl_and_settlement_schema_are_rejected(db):+ clock = FakeClock()++ with pytest.raises(driver.DriverValidationError, match="ttl_seconds"):+ _lease(db, clock, ttl=0)+ with pytest.raises(driver.DriverValidationError, match="clock"):+ _lease(db, lambda: float("nan"))+ with pytest.raises(driver.DriverValidationError, match="expiry"):+ _lease(db, FakeClock(1e308), ttl=1e308)++ identity = _identity()+ lease = _lease(db, clock)+ _admit(db, identity, clock)+ attempt = driver.start_task(+ db,+ identity,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ with pytest.raises(driver.DriverValidationError, match="JSON-serializable"):+ driver.settle_task(+ db,+ attempt,+ settlement_id="settlement-1",+ status="settled",+ result={"bad": object()},+ clock=clock,+ )+++def test_renewal_never_shortens_an_active_lease(db):+ clock = FakeClock()+ lease = _lease(db, clock, ttl=30)+ clock.advance(1)++ renewed = driver.renew_lease(db, lease, ttl_seconds=2, clock=clock)++ assert renewed.expires_at == lease.expires_atdiff --git a/tests/gateway/test_hosted_room_gateway_lifecycle.py b/tests/gateway/test_hosted_room_gateway_lifecycle.pynew file mode 100644index 00000000000..fe692d41cca--- /dev/null+++ b/tests/gateway/test_hosted_room_gateway_lifecycle.py@@ -0,0 +1,234 @@+"""Messaging-gateway ownership tests for the hosted Group Chat worker."""++from __future__ import annotations++import asyncio+import threading+import time+from types import SimpleNamespace++import pytest++from gateway import hosted_room_driver, hosted_rooms+from gateway.run import GatewayRunner+from tui_gateway.hosted_room_service import HostedRoomService+++class _RPC:+ def __init__(self) -> None:+ self.sessions = {}+ self.submits = []++ def resolve_exact(self, *, profile, title, source):+ del source+ return self.sessions.get((profile, title))++ def create(self, *, profile, title, source):+ del source+ session = {"session_id": f"{profile}-session", "title": title}+ self.sessions[(profile, title)] = session+ return session++ def resume(self, *, profile, session_id, source):+ del profile, source+ return {"session_id": session_id}++ def submit(self, **kwargs):+ self.submits.append(kwargs["profile"])+ kwargs["on_terminal"]({+ "status": "settled",+ "text": f"reply from {kwargs['profile']}",+ })+ return {"accepted": True}++ def history(self, **kwargs):+ del kwargs+ return []++ def info(self, **kwargs):+ del kwargs+ return {"active": False, "task_id": None}++ def interrupt(self, **kwargs):+ del kwargs+ raise AssertionError("gateway lifecycle must not interrupt room work")+++def _server():+ return SimpleNamespace(_methods={}, _sessions={}, _sessions_lock=threading.Lock())+++def _service(db_path, *, profiles=("default",)):+ service = HostedRoomService(_server(), db_path=db_path)+ rpc = _RPC()+ service.rpc = rpc+ service.runtime.rpc = rpc+ service.local_profiles = lambda: profiles+ return service, rpc+++def _wait_for(predicate, timeout=3.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ raise AssertionError("condition did not settle before timeout")+++async def test_messaging_gateway_supervisor_starts_without_dashboard(monkeypatch):+ from tui_gateway import methods_groups++ state = {"running": False, "starts": 0}++ class Runtime:+ def status(self):+ return {"running": state["running"], "stopping": False}++ service = SimpleNamespace(runtime=Runtime())++ def get_service():+ return service if state["running"] else None++ def start_service():+ state["starts"] += 1+ state["running"] = True+ return service++ monkeypatch.setattr(methods_groups, "get_hosted_room_service", get_service)+ monkeypatch.setattr(methods_groups, "start_hosted_room_service", start_service)++ runner = GatewayRunner.__new__(GatewayRunner)+ started = await runner._ensure_hosted_room_worker()+ assert started is service+ assert state == {"running": True, "starts": 1}++ # A dead child is restarted, while a healthy one is left alone.+ await runner._ensure_hosted_room_worker()+ assert state["starts"] == 1+ state["running"] = False+ await runner._ensure_hosted_room_worker()+ assert state["starts"] == 2+++async def test_dead_room_worker_is_restarted_by_gateway_task_supervision(monkeypatch):+ from tui_gateway import methods_groups++ starts = {"count": 0}++ def fail_start():+ starts["count"] += 1+ raise RuntimeError("worker unavailable")++ monkeypatch.setattr(methods_groups, "get_hosted_room_service", lambda: None)+ monkeypatch.setattr(methods_groups, "start_hosted_room_service", fail_start)+ monkeypatch.setattr(GatewayRunner, "_MAX_SUPERVISED_RESTARTS", 1)+ monkeypatch.setattr(+ GatewayRunner,+ "_supervised_backoff",+ staticmethod(lambda _attempt: 0),+ )++ runner = GatewayRunner.__new__(GatewayRunner)+ runner._running = True+ runner._background_tasks = set()+ runner._spawn_supervised(+ lambda: runner._hosted_room_worker_watcher(interval=0),+ "hosted_room_worker",+ )++ for _ in range(200):+ if starts["count"] == 2 and not runner._background_tasks:+ break+ await asyncio.sleep(0.01)+ runner._running = False++ assert starts["count"] == 2+ assert runner._background_tasks == set()+++def test_gateway_restart_resumes_queued_room_for_multiplexed_profile(tmp_path):+ db = tmp_path / "state.db"+ first, _ = _service(db, profiles=("default", "ops"))+ first.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {+ "member_id": "default",+ "profile": "default",+ "handle": "hermes",+ },+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ first.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops inspect", "thread_id": "thread-1"},+ )+ assert (+ len(hosted_room_driver.list_tasks(db, room_id="room-1", status="queued")) == 1+ )++ resumed, rpc = _service(db, profiles=("default", "ops"))+ resumed.start()+ try:+ _wait_for(+ lambda: any(+ event["kind"] == "message.member"+ for event in hosted_rooms.read_events(+ db, room_id="room-1", since_seq=0+ )["events"]+ )+ )+ finally:+ assert resumed.stop(timeout=1.0)++ assert rpc.submits == ["ops"]+ assert hosted_room_driver.list_tasks(db, room_id="room-1", status="settled")+++def test_dashboard_and_gateway_workers_share_one_fenced_execution_owner(tmp_path):+ db = tmp_path / "state.db"+ gateway, gateway_rpc = _service(db, profiles=("default", "ops"))+ dashboard, dashboard_rpc = _service(db, profiles=("default", "ops"))+ gateway.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {+ "member_id": "default",+ "profile": "default",+ "handle": "hermes",+ },+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ gateway.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops inspect", "thread_id": "thread-1"},+ )++ gateway.start()+ dashboard.start()+ try:+ _wait_for(+ lambda: any(+ event["kind"] == "message.member"+ for event in hosted_rooms.read_events(+ db, room_id="room-1", since_seq=0+ )["events"]+ )+ )+ time.sleep(0.05)+ finally:+ assert gateway.stop(timeout=1.0)+ assert dashboard.stop(timeout=1.0)++ assert len(gateway_rpc.submits) + len(dashboard_rpc.submits) == 1+ events = hosted_rooms.read_events(db, room_id="room-1", since_seq=0)["events"]+ assert sum(event["kind"] == "message.member" for event in events) == 1diff --git a/tests/gateway/test_hosted_room_local_boundary.py b/tests/gateway/test_hosted_room_local_boundary.pynew file mode 100644index 00000000000..46c577e9f90--- /dev/null+++ b/tests/gateway/test_hosted_room_local_boundary.py@@ -0,0 +1,38 @@+"""Dependency boundary for the same-gateway hosted-room backend."""++from pathlib import Path+++ROOT = Path(__file__).resolve().parents[2]+LOCAL_ROOM_MODULES = (+ "gateway/hosted_room_discussion.py",+ "gateway/hosted_room_driver.py",+ "gateway/hosted_room_policy_checkpoint.py",+ "tui_gateway/hosted_room_driver.py",+ "tui_gateway/hosted_room_service.py",+ "tui_gateway/hosted_room_server_rpc.py",+ "tui_gateway/methods_groups.py",+)+FORBIDDEN_SURFACES = (+ "apps/desktop",+ "attachments",+ "artifact",+ "gateway.platforms",+ "hosted_room_links",+ "hosted_room_peer",+ "messaging_refs",+ "roomlink",+ "transport_resolver",+ "turn.handoff",+)+++def test_local_room_modules_do_not_depend_on_excluded_surfaces():+ violations = {}+ for relative_path in LOCAL_ROOM_MODULES:+ source = (ROOT / relative_path).read_text(encoding="utf-8").lower()+ found = [token for token in FORBIDDEN_SURFACES if token in source]+ if found:+ violations[relative_path] = found++ assert violations == {}diff --git a/tests/gateway/test_hosted_rooms.py b/tests/gateway/test_hosted_rooms.pyindex 80c9fdbf8d8..3379b347a7e 100644--- a/tests/gateway/test_hosted_rooms.py+++ b/tests/gateway/test_hosted_rooms.py@@ -8,8 +8,10 @@ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutorimport pytest+from gateway import hosted_room_driver as driverfrom gateway import hosted_rooms as roomsimport hermes_state+from gateway.hosted_room_policy_checkpoint import HostedRoomPolicyCheckpointfrom hermes_state import SessionDBUSER = {"kind": "user", "id": "desktop-user", "display_name": "User"}@@ -396,7 +398,7 @@ def test_authority_scoped_events_require_gateway_and_epoch(tmp_path):_create(db)with pytest.raises(rooms.HostedRoomError, match="authority_gateway_id"):- _append(+ rooms.append_event(db,room_id="room-1",event_id="turn-1",@@ -927,6 +929,147 @@ def test_byte_pressure_pruning_keeps_retired_room_id_reserved(_assert_retired_identity_stays_reserved(db, "room-full", fresh_id="room-new")+def test_tombstone_pruning_owns_only_room_log_driver_and_policy_tables(tmp_path):+ db = tmp_path / "state.db"+ _create(db)+ identity = driver.TaskIdentity(+ room_id="room-1",+ task_id="task-1",+ thread_id="thread-1",+ turn_id="turn-1",+ )+ driver.admit_task(+ db,+ identity,+ payload={+ "target_profile": "ops",+ "prompt": "Inspect.",+ "source_event_seq": 1,+ },+ clock=lambda: 20,+ )+ driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id="gateway-a",+ authority_epoch=1,+ process_generation="process-a",+ ttl_seconds=30,+ clock=lambda: 20,+ )+ HostedRoomPolicyCheckpoint(db)+ _disband(db, room_id="room-1", now=50)+ with sqlite3.connect(db) as conn:+ conn.execute(+ """INSERT INTO hosted_room_policy_cursors(+ room_id, through_seq, stopped_through_seq, updated_at+ ) VALUES ('room-1', 1, 0, 50)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_threads+ VALUES ('room-1', 'thread-1', 'user-1', 1, 0)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_events+ VALUES ('room-1', 'thread-1', 'user-1', 1, '{}')"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_watermarks+ VALUES ('room-1', 'thread-1', 'ops', 1)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_publications+ VALUES ('room-1', 'task-1', 'turn.settled', 0, 1)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_transcript+ VALUES (+ 'room-1', 'thread-1', 1, 'message.user', NULL+ )"""+ )+ conn.execute(+ """CREATE TABLE hosted_room_messaging_refs (+ room_id TEXT NOT NULL,+ marker TEXT NOT NULL+ )"""+ )+ conn.execute(+ """INSERT INTO hosted_room_policy_transcript_state+ VALUES ('room-1', 1)"""+ )+ conn.execute(+ """INSERT INTO hosted_room_messaging_refs+ VALUES ('room-1', 'outside-pr-b')"""+ )++ assert (+ rooms.prune_disbanded_rooms(+ db,+ now=50 + rooms.DISBANDED_ROOM_RETENTION_SECONDS + 1,+ )+ == 1+ )+ with sqlite3.connect(db) as conn:+ for table in (+ "hosted_rooms",+ "hosted_room_events",+ "hosted_room_driver_tasks",+ "hosted_room_driver_leases",+ "hosted_room_policy_cursors",+ "hosted_room_policy_threads",+ "hosted_room_policy_events",+ "hosted_room_policy_watermarks",+ "hosted_room_policy_publications",+ "hosted_room_policy_transcript",+ "hosted_room_policy_transcript_state",+ ):+ assert conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] == 0+ assert (+ conn.execute("SELECT marker FROM hosted_room_messaging_refs").fetchone()[0]+ == "outside-pr-b"+ )+++def test_policy_sync_cannot_recreate_projection_after_room_pruning(+ tmp_path,+ monkeypatch,+):+ db = tmp_path / "state.db"+ _create(db)+ _append(+ db,+ room_id="room-1",+ event_id="user-1",+ kind="message.user",+ actor=USER,+ payload={"text": "hello", "thread_id": "thread-1"},+ now=11,+ )+ checkpoint = HostedRoomPolicyCheckpoint(db)+ original_read = rooms.read_events++ def read_then_prune(*args, **kwargs):+ page = original_read(*args, **kwargs)+ _disband(db, room_id="room-1", now=20)+ rooms.prune_disbanded_rooms(+ db,+ now=20 + rooms.DISBANDED_ROOM_RETENTION_SECONDS + 1,+ )+ return page++ monkeypatch.setattr(rooms, "read_events", read_then_prune)+ with pytest.raises(rooms.RoomNotFoundError, match="not found"):+ checkpoint.sync(room_id="room-1", latest_seq=1)+ with sqlite3.connect(db) as conn:+ for table in (+ "hosted_room_policy_cursors",+ "hosted_room_policy_events",+ "hosted_room_policy_transcript",+ "hosted_room_policy_transcript_state",+ ):+ assert conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] == 0++def test_pre_actor_draft_database_migrates_with_explicit_legacy_identity(tmp_path):db = tmp_path / "state.db"_create_pre_actor_database(db)diff --git a/tests/gateway/test_hosted_rooms_read_path.py b/tests/gateway/test_hosted_rooms_read_path.pynew file mode 100644index 00000000000..983d6eaaf60--- /dev/null+++ b/tests/gateway/test_hosted_rooms_read_path.py@@ -0,0 +1,31 @@+"""Focused lock-behavior coverage for hosted Group Chat reads."""++from gateway import hosted_rooms+++def test_list_rooms_does_not_enter_a_write_transaction_or_prune(tmp_path, monkeypatch):+ db = tmp_path / "state.db"+ hosted_rooms.create_room(+ db,+ room_id="room-1",+ name="Release room",+ members=[{"profile": "default", "handle": "hermes"}],+ authority_gateway_id="gateway-a",+ )++ def reject_write_transaction(*_args, **_kwargs):+ raise AssertionError("list_rooms must not enter a write transaction")++ def reject_prune(*_args, **_kwargs):+ raise AssertionError("list_rooms must not prune retention state")++ monkeypatch.setattr(hosted_rooms, "_transaction", reject_write_transaction)+ monkeypatch.setattr(+ hosted_rooms,+ "_prune_disbanded_rooms_locked",+ reject_prune,+ )++ rows = hosted_rooms.list_rooms(db)++ assert [row["room_id"] for row in rows] == ["room-1"]diff --git a/tests/hermes_cli/test_web_server_boot_handshake.py b/tests/hermes_cli/test_web_server_boot_handshake.pyindex 3b37c242cc0..df3d7c53677 100644--- a/tests/hermes_cli/test_web_server_boot_handshake.py+++ b/tests/hermes_cli/test_web_server_boot_handshake.py@@ -84,6 +84,29 @@ def test_lifespan_warmup_is_synchronous():)+def test_hosted_room_recovery_cannot_block_or_abort_backend_startup(monkeypatch):+ from fastapi.testclient import TestClient+ from tui_gateway import methods_groups++ started = threading.Event()+ release = threading.Event()++ def blocked_failure():+ started.set()+ release.wait(timeout=2.0)+ raise RuntimeError("state.db is locked")++ monkeypatch.setattr(web_server_mod, "_warm_gateway_module", lambda: None)+ monkeypatch.setattr(methods_groups, "start_hosted_room_service", blocked_failure)+ monkeypatch.setattr(methods_groups, "stop_hosted_room_service", lambda **_kwargs: True)++ before = time.perf_counter()+ with TestClient(web_server_mod.app, raise_server_exceptions=False):+ assert started.wait(timeout=1.0)+ assert time.perf_counter() - before < 1.0+ release.set()++# ---------------------------------------------------------------------------# Test 2 — get_status run_in_executor keeps event loop free for other requests# ---------------------------------------------------------------------------diff --git a/tests/tui_gateway/test_auto_continue.py b/tests/tui_gateway/test_auto_continue.pyindex 5910f421b99..950571418f6 100644--- a/tests/tui_gateway/test_auto_continue.py+++ b/tests/tui_gateway/test_auto_continue.py@@ -169,6 +169,60 @@ def test_handled_failure_still_clears_marker(emits, turn_env, marker_home):assert read_turn_marker(marker_home, "session-key") is None+def test_hosted_terminal_receipt_commits_before_marker_retire(+ emits, turn_env, marker_home+):+ observed = []++ def _run(message, **kwargs):+ return {"final_response": "done"}++ def _terminal(receipt):+ observed.append((receipt, read_turn_marker(marker_home, "session-key")))++ agent = types.SimpleNamespace(+ session_id="session-key", run_conversation=_run, clear_interrupt=lambda: None+ )+ session = _session(agent=agent, running=True, source="bot_room")++ server._run_prompt_submit(+ "rid",+ "sid",+ session,+ "do the thing",+ terminal_callback=_terminal,+ )++ assert observed[0][0]["status"] == "settled"+ assert observed[0][1] is not None+ assert read_turn_marker(marker_home, "session-key") is None+++def test_hosted_terminal_receipt_failure_keeps_crash_marker(+ emits, turn_env, marker_home+):+ def _run(message, **kwargs):+ return {"final_response": "done"}++ def _terminal(_receipt):+ raise RuntimeError("state store unavailable")++ agent = types.SimpleNamespace(+ session_id="session-key", run_conversation=_run, clear_interrupt=lambda: None+ )+ session = _session(agent=agent, running=True, source="bot_room")++ server._run_prompt_submit(+ "rid",+ "sid",+ session,+ "do the thing",+ terminal_callback=_terminal,+ )++ assert read_turn_marker(marker_home, "session-key") is not None++def test_continuation_turn_records_attempt_and_original_prompt(emits, turn_env, marker_home):@@ -263,6 +317,20 @@ def test_fresh_marker_schedules_continuation(emits, schedule_env, marker_home):assert ("message.start", "sid", None) in [(e, s, p) for e, s, p in emits]+def test_hosted_room_marker_is_left_to_the_driver(schedule_env, marker_home):+ record_turn_start(marker_home, "session-key", "hosted prompt")++ result = server._maybe_schedule_auto_continue(+ "sid",+ _session(source="bot_room"),+ "session-key",+ )++ assert result is None+ assert not schedule_env+ assert read_turn_marker(marker_home, "session-key") is not None++def test_stale_marker_is_cleared_not_continued(schedule_env, marker_home, monkeypatch):record_turn_start(marker_home, "session-key", "old prompt")monkeypatch.setattr(@@ -373,4 +441,3 @@ def test_failed_agent_build_leaves_marker_for_retry(# ── End to end: continuation runs a real turn and clears the marker ────-diff --git a/tests/tui_gateway/test_groups_methods.py b/tests/tui_gateway/test_groups_methods.pyindex 9f58b612f5f..8ca6abac5c0 100644--- a/tests/tui_gateway/test_groups_methods.py+++ b/tests/tui_gateway/test_groups_methods.py@@ -2,17 +2,24 @@from __future__ import annotations+from types import SimpleNamespace+import pytestimport tui_gateway.server as srv+from tui_gateway import methods_groups@pytest.fixturedef home(tmp_path, monkeypatch):path = tmp_path / ".hermes"path.mkdir()+ (path / "profiles" / "ops").mkdir(parents=True)monkeypatch.setenv("HERMES_HOME", str(path))- return path+ methods_groups.stop_hosted_room_service(timeout=1.0)+ methods_groups.start_hosted_room_service()+ yield path+ methods_groups.stop_hosted_room_service(timeout=1.0)def _result(envelope):@@ -33,7 +40,14 @@ def _create_room():{"room_id": "room-1","name": "Release room",- "members": [{"profile": "ops", "handle": "ops"}],+ "members": [+ {+ "member_id": "default",+ "profile": "default",+ "handle": "hermes",+ },+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],"authority_gateway_id": "gateway-a",},)@@ -41,6 +55,7 @@ def _create_room():def test_capabilities_are_honest_about_the_driver_boundary(home):+ methods_groups.stop_hosted_room_service(timeout=1.0)result = _result(srv._methods["groups.capabilities"](1, {}))assert result["protocol_version"] == 2@@ -52,6 +67,16 @@ def test_capabilities_are_honest_about_the_driver_boundary(home):assert "groups.state" in result["methods"]assert "groups.send" in result["methods"]assert "groups.send" in srv._LONG_HANDLERS+ assert "groups.retry" in result["methods"]+ assert "groups.approve" in result["methods"]+ advertised = [+ str(value).lower() for value in (*result["features"], *result["methods"])+ ]+ assert not any(+ token in value+ for token in ("attachment", "desktop", "messaging", "peer", "roomlink")+ for value in advertised+ )def test_create_list_send_and_log_roundtrip(home):@@ -72,12 +97,12 @@ def test_create_list_send_and_log_roundtrip(home):"room_id": "room-1","event_id": "event-1","actor": {"kind": "user", "id": "desktop-user"},- "payload": {"text": "hello"},+ "payload": {"text": "hello", "thread_id": "thread-1"},},))assert sent["accepted"] is True- assert sent["driver_started"] is False+ assert sent["driver_started"] is Trueassert sent["event"]["seq"] == 1assert sent["event"]["kind"] == "message.user"assert sent["event"]["actor"] == {"kind": "user", "id": "desktop"}@@ -89,7 +114,10 @@ def test_create_list_send_and_log_roundtrip(home):))assert replay["latest_seq"] == replay["cursor"] == 1- assert replay["events"][0]["payload"] == {"text": "hello"}+ assert replay["events"][0]["payload"] == {+ "text": "hello",+ "thread_id": "thread-1",+ }def test_groups_list_returns_bounded_pages(home):@@ -137,7 +165,7 @@ def test_rpc_retry_is_idempotent_and_conflict_is_visible(home):"room_id": "room-1","event_id": "event-1","actor": {"kind": "user", "id": "desktop-user"},- "payload": {"text": "hello"},+ "payload": {"text": "hello", "thread_id": "thread-1"},}first = _result(srv._methods["groups.send"](2, params))repeated = _result(srv._methods["groups.send"](3, params))@@ -149,7 +177,10 @@ def test_rpc_retry_is_idempotent_and_conflict_is_visible(home):conflict = srv._methods["groups.send"](4,- {**params, "payload": {"text": "different"}},+ {+ **params,+ "payload": {"text": "different", "thread_id": "thread-1"},+ },)assert conflict["error"]["code"] == 4111assert "different content" in conflict["error"]["message"]@@ -179,7 +210,7 @@ def test_foreign_authority_cannot_send_or_disband(home):{"room_id": "room-1","event_id": "stale-send",- "payload": {"text": "must not land"},+ "payload": {"text": "must not land", "thread_id": "thread-1"},},)disbanded = srv._methods["groups.disband"](3, {"room_id": "room-1"})@@ -200,7 +231,7 @@ def test_client_event_id_cannot_squat_disband_receipt(home):{"room_id": "room-1","event_id": "system:room-disbanded",- "payload": {"text": "still a user message"},+ "payload": {"text": "still a user message", "thread_id": "thread-1"},},))@@ -221,6 +252,7 @@ def test_client_event_id_cannot_squat_disband_receipt(home):)assert [event["kind"] for event in replay["events"]] == ["message.user",+ "room.stop_requested","room.disbanded",]@@ -234,7 +266,7 @@ def test_send_does_not_trust_client_supplied_actor_identity(home):"room_id": "room-1","event_id": "event-1","actor": {"kind": "user", "id": "spoofed-user"},- "payload": {"text": "hello"},+ "payload": {"text": "hello", "thread_id": "thread-1"},},))@@ -243,10 +275,14 @@ def test_send_does_not_trust_client_supplied_actor_identity(home):def test_create_ignores_client_supplied_authority_identity(home):+ members = [+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ]created = _result(srv._methods["groups.create"](1,- {"room_id": "legacy-room", "name": "Legacy", "members": []},+ {"room_id": "legacy-room", "name": "Legacy", "members": members},))["room"]retried = _result(@@ -255,7 +291,7 @@ def test_create_ignores_client_supplied_authority_identity(home):{"room_id": "legacy-room","name": "Legacy",- "members": [],+ "members": members,"authority_gateway_id": "spoofed-gateway",},)@@ -269,7 +305,10 @@ def test_create_ignores_client_supplied_authority_identity(home):def test_legacy_room_adoption_emits_one_lineage_receipt(home):from gateway.hosted_rooms import create_room, default_db_path- members = [{"profile": "ops", "handle": "ops"}]+ members = [+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ]create_room(default_db_path(),room_id="legacy-room",@@ -285,9 +324,7 @@ def test_legacy_room_adoption_emits_one_lineage_receipt(home):{"room_id": "legacy-room", "name": "Legacy", "members": members},))["room"]- state = _result(- srv._methods["groups.state"](3, {"room_id": "legacy-room"})- )["room"]+ state = _result(srv._methods["groups.state"](3, {"room_id": "legacy-room"}))["room"]assert adopted["adopted"] is Trueassert adopted["authority_gateway_id"] == _server_authority()@@ -327,7 +364,110 @@ def test_legacy_room_adoption_emits_one_lineage_receipt(home):)def test_invalid_or_unknown_room_returns_contract_error(home, method_name, params):result = srv._methods[method_name](1, params)- assert result["error"]["code"] in {4110, 4111, 4112}+ assert result["error"]["code"] in {4110, 4111, 4112, 5111, 5112}+++def test_retry_and_approval_controls_forward_only_exact_local_coordinates(+ home, monkeypatch+):+ calls = []+ identity = SimpleNamespace(+ room_id="room-1",+ task_id="task-1",+ thread_id="thread-1",+ turn_id="turn-1",+ )+ service = SimpleNamespace(+ retry_room_task=lambda room_id, task_id: (+ calls.append(("retry", room_id, task_id))+ or {+ "identity": identity,+ "status": "queued",+ "execution_generation": 1,+ "cancel_generation": 0,+ }+ ),+ approve_room_task=lambda room_id, **kwargs: (+ calls.append(("approve", room_id, kwargs)) or {"resolved": 1}+ ),+ )+ monkeypatch.setattr(srv, "get_hosted_room_service", lambda: service)++ retried = _result(+ srv._methods["groups.retry"](+ 1,+ {"room_id": "room-1", "task_id": "task-1"},+ )+ )+ approved = _result(+ srv._methods["groups.approve"](+ 2,+ {+ "room_id": "room-1",+ "member_id": "ops",+ "task_id": "task-1",+ "execution_generation": 1,+ "request_id": "approval-1",+ "choice": "once",+ },+ )+ )++ assert retried["task"] == {+ "room_id": "room-1",+ "task_id": "task-1",+ "thread_id": "thread-1",+ "turn_id": "turn-1",+ "status": "queued",+ "execution_generation": 1,+ "cancel_generation": 0,+ }+ assert approved == {"approved": True, "result": {"resolved": 1}}+ assert calls == [+ ("retry", "room-1", "task-1"),+ (+ "approve",+ "room-1",+ {+ "member_id": "ops",+ "task_id": "task-1",+ "execution_generation": 1,+ "choice": "once",+ "request_id": "approval-1",+ },+ ),+ ]+++ ("method_name", "params"),+ [+ ("groups.create", {"room_id": "room-1", "name": "Room", "members": []}),+ ("groups.send", {"room_id": "room-1", "event_id": "event-1", "payload": {}}),+ ("groups.disband", {"room_id": "room-1"}),+ ("groups.stop", {"room_id": "room-1"}),+ ("groups.retry", {"room_id": "room-1", "task_id": "task-1"}),+ (+ "groups.approve",+ {+ "room_id": "room-1",+ "member_id": "ops",+ "task_id": "task-1",+ "execution_generation": 1,+ "request_id": "approval-1",+ "choice": "once",+ },+ ),+ ],+)+def test_mutating_controls_fail_closed_without_a_supervised_worker(+ home, monkeypatch, method_name, params+):+ monkeypatch.setattr(srv, "get_hosted_room_service", lambda: None)++ result = srv._methods[method_name](1, params)++ assert result["error"]["code"] in {4115, 4123}def test_disband_tombstones_room(home):@@ -337,9 +477,9 @@ def test_disband_tombstones_room(home):assert first["tombstone"]["idempotent"] is Falseassert repeated["tombstone"]["idempotent"] is Trueassert _result(srv._methods["groups.list"](5, {}))["rooms"] == []- deleted = _result(- srv._methods["groups.list"](6, {"include_disbanded": True})- )["rooms"]+ deleted = _result(srv._methods["groups.list"](6, {"include_disbanded": True}))[+ "rooms"+ ]assert deleted[0]["disbanded_at"] == first["tombstone"]["disbanded_at"]replay = _result(srv._methods["groups.log"](@@ -347,12 +487,19 @@ def test_disband_tombstones_room(home):{"room_id": "room-1", "include_disbanded": True},))- assert [event["kind"] for event in replay["events"]] == ["room.disbanded"]+ assert [event["kind"] for event in replay["events"]] == [+ "room.stop_requested",+ "room.disbanded",+ ]def test_pruned_room_send_and_log_report_expired_history(home, monkeypatch):from gateway import hosted_rooms+ members = [+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ]_create_room()monkeypatch.setattr(hosted_rooms, "MAX_DISBANDED_ROOM_TOMBSTONES", 0)_result(srv._methods["groups.disband"](2, {"room_id": "room-1"}))@@ -367,7 +514,7 @@ def test_pruned_room_send_and_log_report_expired_history(home, monkeypatch):{"room_id": "room-1","event_id": "stale-send",- "payload": {"text": "stale"},+ "payload": {"text": "stale", "thread_id": "thread-1"},},)logged = srv._methods["groups.log"](@@ -375,19 +522,21 @@ def test_pruned_room_send_and_log_report_expired_history(home, monkeypatch):{"room_id": "room-1", "include_disbanded": True},)+ assert sent["error"]["code"] == 4111, sent+ assert logged["error"]["code"] == 4112, loggedassert sent["error"]["data"] == {"reason": "room_history_expired"}assert logged["error"]["data"] == {"reason": "room_history_expired"}assert "permanently retired" in sent["error"]["message"]recreated = srv._methods["groups.create"](6,- {"room_id": "room-1", "name": "Replacement", "members": []},+ {"room_id": "room-1", "name": "Replacement", "members": members},)assert recreated["error"]["code"] == 4110created = _result(srv._methods["groups.create"](7,- {"room_id": "room-new", "name": "Fresh", "members": []},+ {"room_id": "room-new", "name": "Fresh", "members": members},))assert created["room"]["room_id"] == "room-new"diff --git a/tests/tui_gateway/test_hosted_room_driver_runtime.py b/tests/tui_gateway/test_hosted_room_driver_runtime.pynew file mode 100644index 00000000000..b4371ba8261--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_driver_runtime.py@@ -0,0 +1,1366 @@+"""Runtime tests for the hosted-room session adapter."""++from __future__ import annotations++import threading+import time+from contextlib import contextmanager+from pathlib import Path+from typing import Any++import pytest++from gateway import hosted_room_driver as state+from gateway import hosted_rooms+from tui_gateway.hosted_room_driver import (+ MAX_TERMINAL_TEXT_BYTES,+ ROOM_SESSION_SOURCE,+ HostedRoomBinding,+ HostedRoomRuntime,+ room_session_title,+)+++ROOM_ID = "room-1"+PROFILE = "ops"+BINDING = HostedRoomBinding(+ room_id=ROOM_ID,+ gateway_id="gateway-a",+ authority_epoch=1,+)+++class RecordingTurnLocks:+ """Record the profile lock and expose ownership to the fake RPC."""++ def __init__(self) -> None:+ self.events: list[tuple[str, str]] = []+ self.local = threading.local()++ @contextmanager+ def __call__(self, profile: str):+ self.events.append(("lock-enter", profile))+ self.local.profile = profile+ try:+ yield+ finally:+ self.events.append(("lock-exit", profile))+ self.local.profile = None++ def held_for(self, profile: str) -> bool:+ return getattr(self.local, "profile", None) == profile+++class FakeSessionRPC:+ """Normalized in-memory session adapter with no model or network."""++ def __init__(+ self,+ *,+ auto_complete: bool = True,+ required_lock: RecordingTurnLocks | None = None,+ ) -> None:+ self.auto_complete = auto_complete+ self.required_lock = required_lock+ self.calls: list[tuple[str, dict[str, Any]]] = []+ self.sessions: dict[tuple[str, str], dict[str, Any]] = {}+ self.states: dict[str, dict[str, Any]] = {}+ self.submitted = threading.Event()+ self.on_interrupt = None+ self.on_info = None+ self.history_failures = 0+ self._next_id = 1+ self._lock = threading.Lock()++ def _assert_lock(self, profile: str) -> None:+ if self.required_lock is not None:+ assert self.required_lock.held_for(profile)++ def add_session(+ self,+ *,+ profile: str = PROFILE,+ title: str = room_session_title(ROOM_ID),+ active: bool = False,+ task_id: str | None = None,+ history: list[dict[str, Any]] | None = None,+ ) -> str:+ with self._lock:+ session_id = f"session-{self._next_id}"+ self._next_id += 1+ session = {"session_id": session_id, "title": title}+ self.sessions[(profile, title)] = session+ self.states[session_id] = {+ "active": active,+ "task_id": task_id,+ "execution_generation": None,+ "history": list(history or []),+ "on_terminal": None,+ "pending_approval": None,+ }+ return session_id++ def complete(+ self,+ task_id: str,+ *,+ content: str = "Finished once.",+ status: str = "settled",+ ) -> None:+ callback = None+ receipt = None+ with self._lock:+ for session_id, session_state in self.states.items():+ if session_state["task_id"] != task_id:+ continue+ receipt = {+ "role": "assistant",+ "task_id": task_id,+ "execution_generation": session_state["execution_generation"],+ "status": status,+ "message_id": f"reply:{task_id}",+ "content": content,+ }+ session_state["history"].append(receipt)+ session_state["active"] = False+ callback = session_state.get("on_terminal")+ self.calls.append(("complete", {"session_id": session_id}))+ break+ if receipt is None:+ raise AssertionError(f"no active session for {task_id}")+ if callback is not None:+ callback({+ "status": status,+ "settlement_id": receipt["message_id"],+ "message_id": receipt["message_id"],+ "text": content,+ })++ def resolve_exact(self, *, profile: str, title: str, source: str):+ self._assert_lock(profile)+ params = {"profile": profile, "title": title, "source": source}+ self.calls.append(("resolve_exact", params))+ with self._lock:+ session = self.sessions.get((profile, title))+ return dict(session) if session is not None else None++ def create(self, *, profile: str, title: str, source: str):+ self._assert_lock(profile)+ params = {"profile": profile, "title": title, "source": source}+ self.calls.append(("create", params))+ session_id = self.add_session(profile=profile, title=title)+ return {"session_id": session_id, "title": title}++ def resume(self, *, profile: str, session_id: str, source: str):+ self._assert_lock(profile)+ params = {+ "profile": profile,+ "session_id": session_id,+ "source": source,+ }+ self.calls.append(("resume", params))+ return {"session_id": session_id}++ def submit(+ self,+ *,+ profile: str,+ session_id: str,+ prompt: str,+ source: str,+ task: state.TaskIdentity,+ execution_generation: int,+ on_terminal,+ ):+ self._assert_lock(profile)+ params = {+ "profile": profile,+ "session_id": session_id,+ "prompt": prompt,+ "source": source,+ "task": task,+ "execution_generation": execution_generation,+ "on_terminal": on_terminal,+ }+ self.calls.append(("submit", params))+ with self._lock:+ self.states[session_id]["active"] = True+ self.states[session_id]["task_id"] = task.task_id+ self.states[session_id]["execution_generation"] = execution_generation+ self.states[session_id]["on_terminal"] = on_terminal+ self.submitted.set()+ if self.auto_complete:+ self.complete(task.task_id)+ return {"accepted": True}++ def history(self, *, profile: str, session_id: str, source: str):+ self._assert_lock(profile)+ params = {+ "profile": profile,+ "session_id": session_id,+ "source": source,+ }+ self.calls.append(("history", params))+ if self.history_failures > 0:+ self.history_failures -= 1+ raise RuntimeError("transient history read failed")+ with self._lock:+ return [dict(message) for message in self.states[session_id]["history"]]++ def info(self, *, profile: str, session_id: str, source: str):+ self._assert_lock(profile)+ params = {+ "profile": profile,+ "session_id": session_id,+ "source": source,+ }+ self.calls.append(("info", params))+ with self._lock:+ session_state = self.states[session_id]+ result = {+ "active": session_state["active"],+ "task_id": session_state["task_id"],+ }+ if session_state.get("pending_approval"):+ result["status"] = "waiting_for_approval"+ result["pending_approval"] = dict(session_state["pending_approval"])+ if self.on_info is not None:+ self.on_info()+ return result++ def interrupt(+ self,+ *,+ profile: str,+ session_id: str,+ source: str,+ expected_task_id: str,+ ):+ params = {+ "profile": profile,+ "session_id": session_id,+ "source": source,+ "expected_task_id": expected_task_id,+ }+ with self._lock:+ current = self.states[session_id]+ if not current["active"] or current["task_id"] != expected_task_id:+ self.calls.append(("interrupt_skipped", params))+ return {"interrupted": False}+ current["active"] = False+ self.calls.append(("interrupt", params))+ if self.on_interrupt is not None:+ self.on_interrupt()+ return {"interrupted": True}+++class SelectiveCompletionRPC(FakeSessionRPC):+ """Keep selected local profiles running while peers complete normally."""++ def __init__(self, *, waiting_profiles: set[str]) -> None:+ super().__init__()+ self.waiting_profiles = waiting_profiles+ self._submit_mode_lock = threading.Lock()++ def submit(self, **kwargs):+ with self._submit_mode_lock:+ original = self.auto_complete+ self.auto_complete = kwargs["profile"] not in self.waiting_profiles+ try:+ return super().submit(**kwargs)+ finally:+ self.auto_complete = original+++def db(tmp_path: Path) -> Path:+ path = tmp_path / "state.db"+ hosted_rooms.create_room(+ path,+ room_id=ROOM_ID,+ name="Release room",+ members=[{"profile": PROFILE, "handle": PROFILE}],+ authority_gateway_id=BINDING.gateway_id,+ now=time.time(),+ )+ return path+++def _identity(task_id: str = "task-1") -> state.TaskIdentity:+ return state.TaskIdentity(+ room_id=ROOM_ID,+ task_id=task_id,+ thread_id="thread-1",+ turn_id=f"turn-{task_id}",+ )+++def _admit(+ db: Path,+ identity: state.TaskIdentity,+ *,+ prompt: str = "Inspect the release candidate.",+) -> None:+ state.admit_task(+ db,+ identity,+ payload={+ "target_profile": PROFILE,+ "prompt": prompt,+ "source_event_seq": 1,+ },+ clock=time.time,+ )+++def _runtime(+ db: Path,+ rpc: FakeSessionRPC,+ locks: RecordingTurnLocks | None = None,+ **kwargs,+) -> HostedRoomRuntime:+ return HostedRoomRuntime(+ db_path=db,+ rooms=[BINDING],+ rpc=rpc,+ turn_lock=locks or RecordingTurnLocks(),+ lease_ttl_seconds=kwargs.pop("lease_ttl_seconds", 0.4),+ poll_interval_seconds=kwargs.pop("poll_interval_seconds", 0.01),+ **kwargs,+ )+++def _wait_for(predicate, *, timeout: float = 2.0) -> None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ raise AssertionError("condition was not reached before timeout")+++def test_runtime_uses_unique_process_generation(db: Path):+ first = _runtime(db, FakeSessionRPC())+ second = _runtime(db, FakeSessionRPC())++ assert first.process_generation != second.process_generation+ assert len(first.process_generation) == 32++[email protected]("value", [0, True])+def test_room_concurrency_bound_must_be_a_positive_integer(db: Path, value):+ with pytest.raises(ValueError, match="max_concurrent_rooms"):+ _runtime(db, FakeSessionRPC(), max_concurrent_rooms=value)+++def test_waiting_room_does_not_block_an_independent_local_room(tmp_path: Path):+ db = tmp_path / "state.db"+ bindings = [+ HostedRoomBinding("room-waiting", "gateway-a", 1),+ HostedRoomBinding("room-healthy", "gateway-a", 1),+ ]+ identities = [+ state.TaskIdentity("room-waiting", "task-waiting", "thread-a", "turn-a"),+ state.TaskIdentity("room-healthy", "task-healthy", "thread-b", "turn-b"),+ ]+ profiles = ["profile-waiting", "profile-healthy"]+ for binding, identity, profile in zip(bindings, identities, profiles):+ hosted_rooms.create_room(+ db,+ room_id=binding.room_id,+ name=binding.room_id,+ members=[{"profile": profile, "handle": profile}],+ authority_gateway_id=binding.gateway_id,+ now=time.time(),+ )+ state.admit_task(+ db,+ identity,+ payload={+ "target_profile": profile,+ "prompt": f"Run {binding.room_id}.",+ "source_event_seq": 1,+ },+ clock=time.time,+ )++ rpc = SelectiveCompletionRPC(waiting_profiles={"profile-waiting"})+ runtime = HostedRoomRuntime(+ db_path=db,+ rooms=bindings,+ rpc=rpc,+ turn_lock=RecordingTurnLocks(),+ lease_ttl_seconds=0.4,+ poll_interval_seconds=0.01,+ max_concurrent_rooms=2,+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identities[1])["status"] == "settled")+ _wait_for(lambda: state.get_task(db, identities[0])["status"] == "running")+ assert state.get_task(db, identities[0])["status"] == "running"+ _wait_for(lambda: len(runtime.status()["current_tasks"]) == 1)+ assert len(runtime.status()["current_tasks"]) == 1+ assert runtime.stop(timeout=1.0)+++def test_rotated_bounded_scheduler_eventually_runs_later_room(tmp_path: Path):+ db = tmp_path / "state.db"+ bindings = [+ HostedRoomBinding(f"room-{index}", "gateway-a", 1) for index in range(1, 4)+ ]+ for binding in bindings:+ hosted_rooms.create_room(+ db,+ room_id=binding.room_id,+ name=binding.room_id,+ members=[{"profile": PROFILE, "handle": PROFILE}],+ authority_gateway_id=binding.gateway_id,+ now=time.time(),+ )+ identity = state.TaskIdentity(+ "room-3",+ "task-room-3",+ "thread-room-3",+ "turn-room-3",+ )+ state.admit_task(+ db,+ identity,+ payload={+ "target_profile": PROFILE,+ "prompt": "Run the later room.",+ "source_event_seq": 1,+ },+ clock=time.time,+ )+ runtime = HostedRoomRuntime(+ db_path=db,+ rooms=bindings,+ rpc=FakeSessionRPC(),+ turn_lock=RecordingTurnLocks(),+ lease_ttl_seconds=0.4,+ poll_interval_seconds=0.01,+ max_concurrent_rooms=2,+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)+++def test_queued_task_routes_profile_and_credentials_without_overrides(db: Path):+ identity = _identity()+ _admit(db, identity, prompt="Use the configured profile credentials.")+ rpc = FakeSessionRPC()+ runtime = _runtime(db, rpc)++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ create = next(params for method, params in rpc.calls if method == "create")+ submit = next(params for method, params in rpc.calls if method == "submit")+ assert create == {+ "profile": PROFILE,+ "title": f"Group: {ROOM_ID}",+ "source": ROOM_SESSION_SOURCE,+ }+ assert submit["profile"] == PROFILE+ assert submit["source"] == ROOM_SESSION_SOURCE+ assert submit["prompt"] == "Use the configured profile credentials."+ assert "model" not in create | submit+ assert "provider" not in create | submit+ assert state.get_task(db, identity)["result"]["text"] == "Finished once."+++def test_worker_settles_without_any_client_transport(db: Path):+ identity = _identity()+ _admit(db, identity)+ runtime = _runtime(db, FakeSessionRPC())++ runtime.start()+ _wait_for(+ lambda: (+ state.get_task(db, identity)["status"] == "settled"+ and runtime.status()["cycles"] >= 1+ )+ )++ assert runtime.status()["running"] is True+ assert runtime.status()["cycles"] >= 1+ assert runtime.stop(timeout=1.0)+++def test_policy_hooks_prepare_and_publish_terminal_idempotently(db: Path):+ identity = _identity()+ _admit(db, identity)+ prepared = []+ published = []+ runtime = _runtime(+ db,+ FakeSessionRPC(),+ prepare_room=lambda binding: prepared.append(binding.room_id),+ publish_terminal=lambda binding, task: published.append((+ binding.room_id,+ task["identity"].task_id,+ task["status"],+ )),+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ assert prepared+ assert published == [(ROOM_ID, identity.task_id, "settled")]+++def test_existing_canonical_session_is_resumed_not_duplicated(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC()+ session_id = rpc.add_session()+ runtime = _runtime(db, rpc)++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ assert not [call for call in rpc.calls if call[0] == "create"]+ resume = next(params for method, params in rpc.calls if method == "resume")+ assert resume == {+ "profile": PROFILE,+ "session_id": session_id,+ "source": ROOM_SESSION_SOURCE,+ }+++def test_local_crash_recovery_keeps_ambiguous_history_explicit_without_resume(+ db: Path,+):+ identity = _identity()+ now = [100.0]++ def clock():+ return now[0]++ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=0.2,+ clock=clock,+ )+ _admit(db, identity)+ state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(+ task_id=identity.task_id,+ history=[+ {+ "role": "assistant",+ "task_id": identity.task_id,+ "execution_generation": 1,+ "status": "settled",+ "message_id": "reply:recovered",+ "content": "Recovered durable answer.",+ }+ ],+ )+ now[0] = 101.0+ runtime = _runtime(+ db,+ rpc,+ clock=clock,+ indeterminate_defer_seconds=5,+ )++ runtime._process_room(BINDING)++ recovered = state.get_task(db, identity)+ assert recovered["status"] == "indeterminate"+ assert recovered["result"] is None+ assert not [call for call in rpc.calls if call[0] == "history"]+ assert [call for call in rpc.calls if call[0] == "info"]+ assert not [call for call in rpc.calls if call[0] == "resume"]+ assert not [call for call in rpc.calls if call[0] == "submit"]+++def test_expired_local_attempt_defers_without_hydrating_or_resubmitting(db: Path):+ identity = _identity()+ now = [100.0]++ def clock():+ return now[0]++ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=0.2,+ clock=clock,+ )+ _admit(db, identity)+ state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(+ task_id=identity.task_id,+ history=[+ {+ "role": "assistant",+ "task_id": identity.task_id,+ "execution_generation": 1,+ "status": "settled",+ "message_id": "reply:expired-recovered",+ "content": "Recovered after lease expiry.",+ }+ ],+ )+ now[0] = 101.0+ runtime = _runtime(+ db,+ rpc,+ clock=clock,+ indeterminate_defer_seconds=0.5,+ )++ runtime._process_room(BINDING)+ now[0] = 102.0+ runtime._process_room(BINDING)++ recovered = state.get_task(db, identity)+ assert recovered["status"] == "deferred"+ assert recovered["result"] == {+ "reason": "member_unavailable",+ "retryable": True,+ }+ assert not [call for call in rpc.calls if call[0] == "history"]+ assert not [call for call in rpc.calls if call[0] == "resume"]+ assert not [call for call in rpc.calls if call[0] == "submit"]+++def test_oversized_terminal_reply_is_bounded_without_waiting_for_deadline(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc, turn_timeout_seconds=30)++ runtime.start()+ assert rpc.submitted.wait(timeout=1.0)+ rpc.complete(+ identity.task_id,+ content="é" * (MAX_TERMINAL_TEXT_BYTES + 100),+ )+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ result = state.get_task(db, identity)["result"]+ assert result["truncated"] is True+ assert len(result["text"].encode("utf-8")) <= MAX_TERMINAL_TEXT_BYTES+ assert result["text"].endswith("share the full result as a file.]")+++def test_turn_deadline_stops_exact_attempt_and_publishes_durable_failure(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ published = []+ runtime = _runtime(+ db,+ rpc,+ active_poll_interval_seconds=0.01,+ turn_timeout_seconds=0.05,+ publish_terminal=lambda _binding, task: published.append(task),+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "failed")+ assert runtime.stop(timeout=1.0)++ failed = state.get_task(db, identity)+ assert failed["result"] == {+ "error": (+ "This Group Chat turn exceeded its configured time limit and was stopped."+ ),+ "reason_code": "turn_deadline_exceeded",+ "timeout_seconds": 0.05,+ }+ assert failed["cancel_id"] == "deadline:1"+ assert [call for call in rpc.calls if call[0] == "interrupt"]+ assert [task["status"] for task in published] == ["failed"]+++def test_deadline_releases_worker_capacity_for_later_room(tmp_path: Path):+ db = tmp_path / "state.db"+ bindings = [+ HostedRoomBinding("room-stuck", "gateway-a", 1),+ HostedRoomBinding("room-healthy", "gateway-a", 1),+ ]+ identities = [+ state.TaskIdentity("room-stuck", "task-stuck", "thread-a", "turn-a"),+ state.TaskIdentity("room-healthy", "task-healthy", "thread-b", "turn-b"),+ ]+ for binding, identity in zip(bindings, identities):+ hosted_rooms.create_room(+ db,+ room_id=binding.room_id,+ name=binding.room_id,+ members=[{"profile": PROFILE, "handle": PROFILE}],+ authority_gateway_id=binding.gateway_id,+ )+ state.admit_task(+ db,+ identity,+ payload={+ "target_profile": PROFILE,+ "prompt": f"Run {binding.room_id}.",+ "source_event_seq": 1,+ },+ clock=time.time,+ )++ class FirstRoomStallsRPC(FakeSessionRPC):+ def submit(self, **kwargs):+ result = super().submit(**kwargs)+ if kwargs["task"].room_id == "room-healthy":+ self.complete(kwargs["task"].task_id)+ return result++ rpc = FirstRoomStallsRPC(auto_complete=False)+ runtime = HostedRoomRuntime(+ db_path=db,+ rooms=bindings,+ rpc=rpc,+ turn_lock=RecordingTurnLocks(),+ lease_ttl_seconds=0.4,+ poll_interval_seconds=0.02,+ active_poll_interval_seconds=0.01,+ turn_timeout_seconds=0.05,+ max_concurrent_rooms=1,+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identities[0])["status"] == "failed")+ _wait_for(lambda: state.get_task(db, identities[1])["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ assert state.get_task(db, identities[0])["result"]["reason_code"] == (+ "turn_deadline_exceeded"+ )+ assert state.get_task(db, identities[1])["status"] == "settled"+++def test_retry_ignores_late_receipt_from_prior_execution_generation(db: Path):+ identity = _identity()+ now = [100.0]++ def clock():+ return now[0]++ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=0.2,+ clock=clock,+ )+ _admit(db, identity)+ old_attempt = state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ now[0] = 101.0+ current_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="manual-recovery",+ ttl_seconds=30,+ clock=clock,+ )+ state.recover_room(db, current_lease, clock=clock)+ state.requeue_indeterminate_task(+ db,+ identity,+ current_lease,+ expected_execution_generation=old_attempt.execution_generation,+ expected_cancel_generation=old_attempt.cancel_generation,+ clock=clock,+ )+ state.release_lease(db, current_lease, clock=clock)+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(+ task_id=identity.task_id,+ history=[+ {+ "role": "assistant",+ "task_id": identity.task_id,+ "execution_generation": old_attempt.execution_generation,+ "status": "settled",+ "message_id": "reply:late-old-attempt",+ "content": "Late old result.",+ }+ ],+ )+ runtime = _runtime(db, rpc, clock=clock)++ runtime.start()+ assert rpc.submitted.wait(1.0)+ time.sleep(0.04)+ assert runtime.stop(timeout=1.0)++ task = state.get_task(db, identity)+ assert task["status"] == "running"+ assert task["execution_generation"] == old_attempt.execution_generation + 1+++def test_active_recovered_turn_is_never_resubmitted(db: Path):+ identity = _identity()+ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=10,+ clock=time.time,+ )+ _admit(db, identity)+ state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=time.time,+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(active=True, task_id=identity.task_id)+ runtime = _runtime(db, rpc)++ runtime.start()+ time.sleep(0.08)+ assert runtime.stop(timeout=1.0)++ assert state.get_task(db, identity)["status"] == "running"+ assert not [call for call in rpc.calls if call[0] == "submit"]+++def test_ambiguous_recovery_remains_indeterminate(db: Path):+ identity = _identity()+ now = [100.0]++ def clock():+ return now[0]++ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=0.2,+ clock=clock,+ )+ _admit(db, identity)+ state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(active=False, task_id=identity.task_id)+ now[0] = 101.0+ runtime = _runtime(db, rpc, clock=clock)++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "indeterminate")+ assert runtime.stop(timeout=1.0)++ assert not [call for call in rpc.calls if call[0] == "submit"]+++def test_offline_member_defers_then_healthy_task_runs_and_retry_is_fenced(+ db: Path,+):+ now = [100.0]++ def clock():+ return now[0]++ first = _identity("task-offline")+ second = state.TaskIdentity(+ room_id=ROOM_ID,+ task_id="task-healthy",+ thread_id="thread-1",+ turn_id="turn-task-healthy",+ )+ state.admit_task(+ db,+ first,+ payload={+ "target_profile": PROFILE,+ "prompt": "Try the offline member.",+ "source_event_seq": 1,+ },+ clock=clock,+ )+ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=1,+ clock=clock,+ )+ old_attempt = state.start_task(+ db,+ first,+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ state.admit_task(+ db,+ second,+ payload={+ "target_profile": PROFILE,+ "prompt": "Continue with the healthy member.",+ "source_event_seq": 2,+ },+ clock=clock,+ )+ now[0] = 102.0+ rpc = FakeSessionRPC()+ published = []+ runtime = _runtime(+ db,+ rpc,+ clock=clock,+ lease_ttl_seconds=30,+ indeterminate_defer_seconds=5,+ publish_terminal=lambda _binding, task: published.append(task),+ )++ runtime._process_room(BINDING)+ assert state.get_task(db, first)["status"] == "indeterminate"+ assert state.get_task(db, second)["status"] == "queued"++ now[0] = 108.0+ runtime._process_room(BINDING)+ assert state.get_task(db, first)["status"] == "deferred"+ assert state.get_task(db, second)["status"] == "settled"+ assert [task["status"] for task in published] == ["deferred", "settled"]+ assert ROOM_ID not in runtime.status()["blocked_rooms"]++ requeued = runtime.retry_indeterminate(first)+ assert requeued["status"] == "queued"+ lease = runtime._leases[ROOM_ID]+ retry_attempt = state.start_task(+ db,+ first,+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ assert retry_attempt.execution_generation == old_attempt.execution_generation + 1+ late_attempt = state.TaskAttempt(+ identity=first,+ lease=lease,+ execution_generation=old_attempt.execution_generation,+ cancel_generation=old_attempt.cancel_generation,+ )+ with pytest.raises(state.StaleTaskError):+ state.settle_task(+ db,+ late_attempt,+ settlement_id="late-old-result",+ status="settled",+ result={"text": "too late"},+ clock=clock,+ )+ state.settle_task(+ db,+ retry_attempt,+ settlement_id="retry-result",+ status="settled",+ result={"text": "retry accepted"},+ clock=clock,+ )+ assert state.get_task(db, first)["result"]["text"] == "retry accepted"+++def test_post_submit_observation_failure_preserves_recoverable_outcome(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.history_failures = 1+ runtime = _runtime(db, rpc)++ runtime.start()+ assert rpc.submitted.wait(1.0)+ _wait_for(+ lambda: (+ "observation failed after submit"+ in str(runtime.status()["last_error"] or "")+ )+ )+ assert state.get_task(db, identity)["status"] == "running"+ rpc.complete(identity.task_id, content="Recovered after a transient read.")+ runtime.wakeup()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ task = state.get_task(db, identity)+ assert task["result"]["text"] == "Recovered after a transient read."+ assert not [call for call in rpc.calls if call[0] == "submit"][1:]+++def test_cancellation_is_persisted_before_interrupt_and_fences_late_result(+ db: Path,+):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc)+ observed_status: list[str] = []+ rpc.on_interrupt = lambda: observed_status.append(+ state.get_task(db, identity)["status"]+ )++ runtime.start()+ assert rpc.submitted.wait(1.0)+ cancelled = runtime.cancel(identity, cancel_id="cancel-user")+ rpc.complete(identity.task_id, content="Too late.")+ runtime.wakeup()+ time.sleep(0.05)+ assert runtime.stop(timeout=1.0)++ assert cancelled["status"] == "cancelled"+ assert observed_status == ["stopping"]+++def test_transient_remote_stop_failure_stays_pending_and_retries(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc)+ original_interrupt = rpc.interrupt+ attempts = 0+ retry_allowed = threading.Event()++ def flaky_interrupt(**kwargs):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise RuntimeError("temporary stop transport failure")+ assert retry_allowed.wait(1.0)+ return original_interrupt(**kwargs)++ rpc.interrupt = flaky_interrupt+ runtime.start()+ assert rpc.submitted.wait(1.0)+ stopping = runtime.cancel(identity, cancel_id="cancel-retry")+ assert stopping["status"] == "stopping"+ assert state.get_task(db, identity)["status"] == "stopping"+ retry_allowed.set()+ runtime.wakeup()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "cancelled")+ assert attempts >= 2+ assert runtime.stop(timeout=1.0)+ assert state.get_task(db, identity)["status"] == "cancelled"+++def test_completion_wins_a_race_with_unacknowledged_stop(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc)++ runtime.start()+ assert rpc.submitted.wait(1.0)++ def finish_only_after_stop_intent():+ if state.get_task(db, identity)["status"] == "stopping":+ rpc.complete(identity.task_id, content="Already done.")++ rpc.on_info = finish_only_after_stop_intent+ result = runtime.cancel(identity, cancel_id="cancel-raced")++ assert result["status"] == "settled"+ assert result["result"]["text"] == "Already done."+ assert runtime.stop(timeout=1.0)+++def test_restart_harvests_completion_before_retrying_durable_stop(db: Path):+ identity = _identity()+ _admit(db, identity)+ now = [100.0]+ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=1.0,+ clock=lambda: now[0],+ )+ attempt = state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=lambda: now[0],+ )+ stopping = state.begin_task_cancel(+ db,+ identity,+ cancel_id="cancel-before-restart",+ expected_cancel_generation=attempt.cancel_generation,+ clock=lambda: now[0],+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(+ active=False,+ task_id=identity.task_id,+ history=[+ {+ "role": "assistant",+ "task_id": identity.task_id,+ "execution_generation": attempt.execution_generation,+ "status": "settled",+ "message_id": "reply-after-stop",+ "content": "Finished before Stop reached the session.",+ }+ ],+ )+ now[0] += 2.0+ runtime = _runtime(+ db,+ rpc,+ process_generation="new-process",+ clock=lambda: now[0],+ )++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ settled = state.get_task(db, identity)+ assert stopping["status"] == "stopping"+ assert settled["result"]["text"] == "Finished before Stop reached the session."+ assert not [call for call in rpc.calls if call[0] == "interrupt"]+++def test_restart_acknowledges_inactive_local_stop_without_memory_marker(db: Path):+ identity = _identity()+ _admit(db, identity)+ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=0.05,+ clock=time.time,+ )+ attempt = state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=time.time,+ )+ state.begin_task_cancel(+ db,+ identity,+ cancel_id="cancel-before-restart",+ expected_cancel_generation=attempt.cancel_generation,+ clock=time.time,+ )+ rpc = FakeSessionRPC(auto_complete=False)+ time.sleep(0.06)+ runtime = _runtime(db, rpc, process_generation="new-process")++ cancelled = runtime.cancel(identity, cancel_id="cancel-before-restart")++ assert cancelled["status"] == "cancelled"+ assert not [call for call in rpc.calls if call[0] == "interrupt"]+++def test_pending_local_approval_is_reported_with_safe_choices(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ actions = []+ runtime = _runtime(+ db,+ rpc,+ pending_action=lambda room_id, member_id, action: actions.append((+ room_id,+ member_id,+ action,+ )),+ )++ runtime.start()+ assert rpc.submitted.wait(1.0)+ session_id = next(iter(rpc.states))+ with rpc._lock:+ rpc.states[session_id]["pending_approval"] = {+ "request_id": "approval-1",+ "command": "pytest -q tests/focused",+ "choices": ["once", "session", "always", "deny"],+ }+ runtime.wakeup()+ _wait_for(lambda: any(action for _room, _member, action in actions))++ _room, member, action = next(item for item in actions if item[2] is not None)+ assert member == PROFILE+ assert action["request_id"] == "approval-1"+ assert action["approval"]["choices"] == ["once", "deny"]+ assert runtime.stop(timeout=1.0)+++def test_cancel_never_interrupts_a_newer_task_in_the_same_session(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc)++ runtime.start()+ assert rpc.submitted.wait(1.0)+ session_id = next(iter(rpc.states))++ def switch_to_newer_task() -> None:+ with rpc._lock:+ rpc.states[session_id]["active"] = True+ rpc.states[session_id]["task_id"] = "task-2"++ rpc.on_info = switch_to_newer_task+ cancelled = runtime.cancel(identity, cancel_id="cancel-old-task")++ assert cancelled["status"] == "stopping"+ assert not [call for call in rpc.calls if call[0] == "interrupt"]+ assert not [call for call in rpc.calls if call[0] == "interrupt_skipped"]+ assert rpc.states[session_id]["active"] is True+ assert rpc.states[session_id]["task_id"] == "task-2"+ assert runtime.stop(timeout=1.0)+++def test_status_reports_room_blocked_on_unresolved_indeterminate_task(db: Path):+ identity = _identity()+ now = [100.0]+ old_lease = state.acquire_lease(+ db,+ room_id=ROOM_ID,+ gateway_id=BINDING.gateway_id,+ authority_epoch=BINDING.authority_epoch,+ process_generation="old-process",+ ttl_seconds=1.0,+ clock=lambda: now[0],+ )+ _admit(db, identity)+ state.start_task(+ db,+ identity,+ old_lease,+ expected_cancel_generation=0,+ clock=lambda: now[0],+ )+ rpc = FakeSessionRPC(auto_complete=False)+ rpc.add_session(active=False, task_id=identity.task_id)+ now[0] += 2.0+ runtime = _runtime(db, rpc, clock=lambda: now[0])++ runtime.start()+ _wait_for(lambda: ROOM_ID in runtime.status()["blocked_rooms"])+ assert runtime.stop(timeout=1.0)++ assert state.get_task(db, identity)["status"] == "indeterminate"+++def test_authority_loss_stops_terminal_commit(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc, lease_ttl_seconds=0.1)++ runtime.start()+ assert rpc.submitted.wait(1.0)+ hosted_rooms.claim_authority(+ db,+ room_id=ROOM_ID,+ expected_gateway_id="gateway-a",+ expected_epoch=1,+ new_gateway_id="gateway-b",+ event_id="claim-gateway-b",+ now=time.time(),+ )+ rpc.complete(identity.task_id)+ runtime.wakeup()+ _wait_for(lambda: runtime.status()["last_error"] is not None)+ assert runtime.stop(timeout=1.0)++ assert state.get_task(db, identity)["status"] == "running"+ assert "authority changed" in runtime.status()["last_error"]+++def test_profile_turn_lock_covers_resolve_submit_and_terminal_observation(db: Path):+ identity = _identity()+ _admit(db, identity)+ locks = RecordingTurnLocks()+ rpc = FakeSessionRPC(required_lock=locks)+ runtime = _runtime(db, rpc, locks)++ runtime.start()+ _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")+ assert runtime.stop(timeout=1.0)++ assert locks.events == [("lock-enter", PROFILE), ("lock-exit", PROFILE)]+ methods = [method for method, _params in rpc.calls]+ assert methods.index("resolve_exact") < methods.index("submit")+ assert methods.index("submit") < methods.index("complete")+ assert "history" not in methods+++def test_stop_is_bounded_and_does_not_interrupt_active_turn(db: Path):+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ runtime = _runtime(db, rpc, poll_interval_seconds=0.01)++ runtime.start()+ assert rpc.submitted.wait(1.0)+ started = time.monotonic()+ stopped = runtime.stop(timeout=0.5)++ assert stopped is True+ assert time.monotonic() - started < 0.5+ assert state.get_task(db, identity)["status"] == "running"+ assert not [call for call in rpc.calls if call[0] == "interrupt"]diff --git a/tests/tui_gateway/test_hosted_room_prompt_fence.py b/tests/tui_gateway/test_hosted_room_prompt_fence.pynew file mode 100644index 00000000000..0592c2f67c2--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_prompt_fence.py@@ -0,0 +1,151 @@+"""Older Desktop clients cannot start a second driver for hosted rooms."""++from __future__ import annotations++import sqlite3+import time++import pytest++from gateway import hosted_rooms+import tui_gateway.server as server+++def _stub_session(monkeypatch, *, title):+ monkeypatch.setattr(+ server,+ "_sess_nowait",+ lambda _params, _rid: (+ {"id": "session-1", "title": title, "source": "bot_room"},+ None,+ ),+ )+++def test_direct_prompt_to_hosted_group_session_is_rejected(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ hosted_rooms.create_room(+ hosted_rooms.default_db_path(),+ room_id="room-hosted",+ name="Hosted room",+ members=[+ {"member_id": "one", "profile": "one", "handle": "one"},+ {"member_id": "two", "profile": "two", "handle": "two"},+ ],+ authority_gateway_id=hosted_rooms.local_authority_gateway_id(),+ )+ _stub_session(monkeypatch, title="Group: room-hosted")++ result = server._methods["prompt.submit"](+ "request-1", {"session_id": "session-1", "text": "continue"}+ )++ assert result["error"]["code"] == 4122+ assert "managed by its gateway" in result["error"]["message"]+++def test_direct_prompt_to_non_hosted_group_reaches_normal_admission(+ tmp_path, monkeypatch+):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ _stub_session(monkeypatch, title="Group: local-only")+ monkeypatch.setattr(+ server,+ "_ensure_active_session_slot",+ lambda _sid, _session: "normal admission reached",+ )++ result = server._methods["prompt.submit"](+ "request-2", {"session_id": "session-1", "text": "continue"}+ )++ assert result["error"] == {"code": 4090, "message": "normal admission reached"}+ assert not hosted_rooms.default_db_path().exists()+++ "legacy_name",+ (+ "Launch room",+ "Ceo, Product Designer, Cfo",+ "Équipe",+ "Alpha/Beta",+ ),+)+def test_direct_prompt_to_legacy_named_group_reaches_normal_admission(+ tmp_path, monkeypatch, legacy_name+):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ _stub_session(monkeypatch, title=f"Group: {legacy_name}")+ monkeypatch.setattr(+ server,+ "_ensure_active_session_slot",+ lambda _sid, _session: "normal admission reached",+ )++ result = server._methods["prompt.submit"](+ "request-legacy", {"session_id": "session-1", "text": "continue"}+ )++ assert result["error"] == {"code": 4090, "message": "normal admission reached"}+++def test_direct_prompt_is_refused_when_room_authority_cannot_be_verified(+ tmp_path, monkeypatch+):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ _stub_session(monkeypatch, title="Group: room-unknown")+ monkeypatch.setattr(+ hosted_rooms,+ "probe_hosted_room",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("disk busy")),+ )++ result = server._methods["prompt.submit"](+ "request-3", {"session_id": "session-1", "text": "continue"}+ )++ assert result["error"]["code"] == 5122+ assert result["error"]["message"] == (+ "Could not verify this group. Try again after the gateway recovers."+ )+++def test_contended_ownership_probe_fails_quickly_without_blocking_socket(+ tmp_path, monkeypatch+):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ db = hosted_rooms.default_db_path()+ hosted_rooms.create_room(+ db,+ room_id="room-busy",+ name="Busy room",+ members=[],+ authority_gateway_id=hosted_rooms.local_authority_gateway_id(),+ )+ _stub_session(monkeypatch, title="Group: room-busy")++ blocker = sqlite3.connect(db)+ blocker.execute("PRAGMA journal_mode=DELETE")+ blocker.execute("BEGIN EXCLUSIVE")+ started = time.monotonic()+ try:+ result = server._methods["prompt.submit"](+ "request-busy", {"session_id": "session-1", "text": "continue"}+ )+ finally:+ blocker.rollback()+ blocker.close()++ assert time.monotonic() - started < 0.5+ assert result["error"]["code"] == 5122diff --git a/tests/tui_gateway/test_hosted_room_server_rpc.py b/tests/tui_gateway/test_hosted_room_server_rpc.pynew file mode 100644index 00000000000..10577bda0cf--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_server_rpc.py@@ -0,0 +1,177 @@+"""Tests for the in-process hosted room session adapter."""++from __future__ import annotations++import threading+from types import SimpleNamespace++import pytest++from gateway.hosted_room_driver import TaskIdentity+from tui_gateway.hosted_room_server_rpc import (+ HostedRoomServerRPC,+ HostedRoomSessionError,+)+++def _server():+ sessions = {}+ calls = []++ def method(name, result):+ def handler(rid, params):+ calls.append((name, params))+ value = result(params) if callable(result) else result+ return {"id": rid, **value}++ return handler++ methods = {+ "session.list": method(+ "session.list",+ {"result": {"sessions": [{"id": "stored", "resolved_id": "tip", "title": "Group: room"}]}},+ ),+ "session.create": method("session.create", {"result": {"session_id": "runtime"}}),+ "session.resume": method("session.resume", {"result": {"session_id": "runtime"}}),+ "session.history": method("session.history", {"result": {"messages": [{"role": "assistant"}]}}),+ "session.interrupt": method("session.interrupt", {"result": {"interrupted": True}}),+ "approval.respond": method("approval.respond", {"result": {"resolved": 1}}),+ "prompt.submit": method("prompt.submit", {"result": {"status": "streaming"}}),+ }+ server = SimpleNamespace(+ _methods=methods,+ _sessions=sessions,+ _sessions_lock=threading.Lock(),+ _pending_approval_request_payload=lambda _session_key: None,+ )+ return server, calls+++def test_routes_exact_hidden_session_and_internal_task_proof():+ server, calls = _server()+ rpc = HostedRoomServerRPC(server)+ task = TaskIdentity("room", "task", "thread", "turn")+ callback = lambda _receipt: None++ assert rpc.resolve_exact(profile="ops", title="Group: room", source="bot_room")["session_id"] == "tip"+ assert rpc.create(profile="ops", title="Group: room", source="bot_room")["session_id"] == "runtime"+ rpc.submit(+ profile="ops",+ session_id="runtime",+ prompt="Do the work",+ source="bot_room",+ task=task,+ execution_generation=2,+ on_terminal=callback,+ )++ create = next(params for method, params in calls if method == "session.create")+ submit = next(params for method, params in calls if method == "prompt.submit")+ assert create["hidden"] is True+ assert create["room_plumbing"] is True+ assert create["follow_profile_config"] is True+ assert create["close_on_disconnect"] is False+ assert submit["_hosted_task"] == {+ "room_id": "room",+ "task_id": "task",+ "thread_id": "thread",+ "turn_id": "turn",+ "execution_generation": 2,+ }+ assert submit["_hosted_terminal_callback"] is callback++ rpc.resume(profile="ops", session_id="stored", source="bot_room")+ resume = next(params for method, params in calls if method == "session.resume")+ assert resume["source"] == "bot_room"+++def test_info_and_interrupt_are_exact_task_scoped():+ server, calls = _server()+ lock = threading.Lock()+ server._sessions["runtime"] = {+ "history_lock": lock,+ "running": True,+ "_hosted_room_task": {"task_id": "task-a"},+ }+ rpc = HostedRoomServerRPC(server)++ assert rpc.info(profile="ops", session_id="runtime", source="bot_room") == {+ "active": True,+ "task_id": "task-a",+ }+ rpc.interrupt(+ profile="ops",+ session_id="runtime",+ source="bot_room",+ expected_task_id="task-a",+ )+ params = next(params for method, params in calls if method == "session.interrupt")+ assert params["expected_hosted_task_id"] == "task-a"+++def test_local_approval_snapshot_and_response_use_exact_request():+ server, calls = _server()+ server._pending_approval_request_payload = lambda session_key: {+ "request_id": "approval-1",+ "command": "pytest -q tests/focused",+ "choices": ["once", "deny"],+ } if session_key == "stored-session" else None+ server._sessions["runtime"] = {+ "history_lock": threading.Lock(),+ "running": True,+ "session_key": "stored-session",+ "_hosted_room_task": {"task_id": "task-a"},+ }+ rpc = HostedRoomServerRPC(server)++ info = rpc.info(profile="ops", session_id="runtime", source="bot_room")+ assert info["status"] == "waiting_for_approval"+ assert info["pending_approval"]["request_id"] == "approval-1"+ assert rpc.approve(+ session_id="runtime",+ request_id="approval-1",+ choice="once",+ ) == {"resolved": 1}+ params = next(params for method, params in calls if method == "approval.respond")+ assert params == {+ "session_id": "runtime",+ "request_id": "approval-1",+ "choice": "once",+ "all": False,+ }+++def test_rpc_errors_are_typed():+ server, _calls = _server()+ server._methods["session.list"] = lambda rid, _params: {+ "id": rid,+ "error": {"code": 4007, "message": "not found"},+ }+ rpc = HostedRoomServerRPC(server)++ with pytest.raises(HostedRoomSessionError) as exc:+ rpc.resolve_exact(profile="ops", title="Group: room", source="bot_room")+ assert exc.value.code == 4007+++def test_prompt_rejection_is_proven_not_admitted():+ server, _calls = _server()+ server._methods["prompt.submit"] = lambda rid, _params: {+ "id": rid,+ "error": {"code": 4121, "message": "session is already busy"},+ }+ rpc = HostedRoomServerRPC(server)++ with pytest.raises(HostedRoomSessionError) as exc:+ rpc.submit(+ profile="ops",+ session_id="runtime",+ prompt="Do the work",+ source="bot_room",+ task=TaskIdentity("room", "task", "thread", "turn"),+ execution_generation=1,+ on_terminal=lambda _receipt: None,+ )++ assert exc.value.code == 4121+ assert exc.value.not_admitted is Truediff --git a/tests/tui_gateway/test_hosted_room_service.py b/tests/tui_gateway/test_hosted_room_service.pynew file mode 100644index 00000000000..3c3664ae36f--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_service.py@@ -0,0 +1,748 @@+"""Integration tests for the hosted Discussion coordinator."""++from __future__ import annotations++import json+import sqlite3+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++from gateway import hosted_room_driver as driver+from gateway import hosted_room_discussion as discussion+from gateway import hosted_rooms+from gateway.hosted_room_policy_checkpoint import MAX_ACTIVE_POLICY_EVENTS+from tui_gateway.hosted_room_service import HostedRoomService+++def _append_room_event(db, **kwargs):+ if kwargs.get("kind") == "message.user":+ room = hosted_rooms.room_state(db, room_id=kwargs["room_id"])+ kwargs.setdefault(+ "authority_gateway_id", str(room["authority_gateway_id"])+ )+ kwargs.setdefault("authority_epoch", int(room["authority_epoch"]))+ return hosted_rooms.append_event(db, **kwargs)+++class _FakeRPC:+ def __init__(self) -> None:+ self.sessions = {}++ def resolve_exact(self, *, profile, title, source):+ return self.sessions.get((profile, title))++ def create(self, *, profile, title, source):+ session = {"session_id": f"{profile}-session", "title": title}+ self.sessions[(profile, title)] = session+ return session++ def resume(self, *, profile, session_id, source):+ return {"session_id": session_id}++ def submit(+ self,+ *,+ profile,+ session_id,+ prompt,+ source,+ task,+ execution_generation,+ on_terminal,+ ):+ on_terminal({"status": "settled", "text": f"reply from {profile}"})+ return {"accepted": True}++ def history(self, *, profile, session_id, source):+ return []++ def info(self, *, profile, session_id, source):+ return {"active": False, "task_id": None}++ def interrupt(self, *, profile, session_id, source, expected_task_id):+ return {"interrupted": True}+++class _PromptRecordingRPC(_FakeRPC):+ def __init__(self) -> None:+ super().__init__()+ self.prompts: list[tuple[str, str]] = []++ def submit(+ self,+ *,+ profile,+ session_id,+ prompt,+ source,+ task,+ execution_generation,+ on_terminal,+ ):+ self.prompts.append((profile, prompt))+ on_terminal({"status": "settled", "text": f"reply from {profile}"})+ return {"accepted": True}+++class _BlockingFirstRPC(_PromptRecordingRPC):+ def __init__(self) -> None:+ super().__init__()+ self.first_started = threading.Event()+ self.release_first = threading.Event()++ def submit(self, **kwargs):+ self.prompts.append((kwargs["profile"], kwargs["prompt"]))+ if len(self.prompts) == 1:+ self.first_started.set()+ assert self.release_first.wait(timeout=2)+ kwargs["on_terminal"](+ {"status": "settled", "text": f"reply from {kwargs['profile']}"}+ )+ return {"accepted": True}+++def _server():+ return SimpleNamespace(_methods={}, _sessions={}, _sessions_lock=threading.Lock())+++def _wait_for(predicate, timeout=2.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ raise AssertionError("condition was not reached")+++def test_create_send_drive_publish_and_replay_without_client_transport(tmp_path: Path):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.rpc = _FakeRPC()+ service.runtime.rpc = service.rpc+ service.local_profiles = lambda: ("default", "ops")+ room = service.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ assert room["room_id"] == "room-1"++ service.start()+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops inspect the release", "thread_id": "thread-1"},+ )+ _wait_for(+ lambda: any(+ event["kind"] == "message.member" for event in service._events("room-1")+ )+ )+ assert service.stop(timeout=1.0)++ events = service._events("room-1")+ assert [event["kind"] for event in events][:3] == [+ "message.user",+ "message.member",+ "turn.settled",+ ]+ assert events[1]["payload"]["text"] == "reply from ops"+ assert service.status("room-1")["working"] is False+++def test_restart_republishes_terminal_task_before_admitting_more(tmp_path: Path):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ event = _append_room_event(+ db,+ room_id="room-1",+ event_id="user-1",+ kind="message.user",+ actor={"kind": "user", "id": "desktop"},+ payload={"text": "@ops inspect", "thread_id": "thread-1"},+ )+ binding = service.bindings()[0]+ service.prepare_room(binding)+ task = driver.list_tasks(db, room_id="room-1", status="queued")[0]+ lease = driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id=binding.gateway_id,+ authority_epoch=binding.authority_epoch,+ process_generation="crashed",+ ttl_seconds=30,+ clock=time.time,+ )+ attempt = driver.start_task(+ db,+ task["identity"],+ lease,+ expected_cancel_generation=0,+ clock=time.time,+ )+ driver.settle_task(+ db,+ attempt,+ settlement_id="reply-1",+ status="settled",+ result={"text": "done"},+ clock=time.time,+ )++ service.prepare_room(binding)+ events = service._events("room-1")+ assert event["seq"] == 1+ assert sum(row["kind"] == "message.member" for row in events) == 1+ assert sum(row["kind"] == "turn.settled" for row in events) == 1+ service.prepare_room(binding)+ replayed = service._events("room-1")+ assert replayed == events+++def test_policy_checkpoint_bounds_replay_after_completed_room_history(+ tmp_path: Path,+ monkeypatch,+):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.local_profiles = lambda: ("default", "ops")+ room = service.create_room(+ room_id="room-1",+ name="Long-running room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "default"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ authority = str(room["authority_gateway_id"])+ rows = []+ for index in range(200):+ user_seq = index * 2 + 1+ activity_seq = user_seq + 1+ thread_id = f"thread-{index}"+ event_id = f"user-{index}"+ rows.extend((+ (+ "room-1",+ user_seq,+ event_id,+ "message.user",+ json.dumps({"kind": "user", "id": "load-test"}),+ None,+ json.dumps({"text": "done", "thread_id": thread_id}),+ float(user_seq),+ ),+ (+ "room-1",+ activity_seq,+ f"activity-{index}",+ "room.activity",+ json.dumps({"kind": "gateway", "id": authority}),+ 1,+ json.dumps({+ "status": "settled",+ "reason_code": "silent_round",+ "thread_id": thread_id,+ "discussion_event_id": event_id,+ }),+ float(activity_seq),+ ),+ ))+ with sqlite3.connect(db) as conn:+ conn.executemany(+ """INSERT INTO hosted_room_events(+ room_id, seq, event_id, kind, actor_json,+ authority_epoch, payload_json, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ rows,+ )+ conn.execute(+ """UPDATE hosted_rooms+ SET next_seq=401, revision=revision+400, updated_at=400+ WHERE room_id='room-1'"""+ )+ _append_room_event(+ db,+ room_id="room-1",+ event_id="user-active",+ kind="message.user",+ actor={"kind": "user", "id": "desktop"},+ payload={"text": "Review this", "thread_id": "thread-active"},+ now=401,+ )++ original_read_events = hosted_rooms.read_events+ reads = {"calls": 0, "rows": 0}++ def counted_read_events(*args, **kwargs):+ page = original_read_events(*args, **kwargs)+ reads["calls"] += 1+ reads["rows"] += len(page["events"])+ return page++ monkeypatch.setattr(hosted_rooms, "read_events", counted_read_events)+ binding = service.bindings()[0]+ service.prepare_room(binding)+ assert reads["rows"] == 401+ snapshot = service._policy_snapshot(hosted_rooms.room_state(db, room_id="room-1"))+ assert len(snapshot.events) == 1+ assert len(snapshot.events) <= MAX_ACTIVE_POLICY_EVENTS+ with sqlite3.connect(db) as conn:+ assert (+ conn.execute("SELECT COUNT(*) FROM hosted_room_policy_events").fetchone()[0]+ == 1+ )+ assert (+ conn.execute("SELECT COUNT(*) FROM hosted_room_policy_threads").fetchone()[+ 0+ ]+ == 1+ )++ reads.update(calls=0, rows=0)+ service.prepare_room(binding)+ assert reads == {"calls": 0, "rows": 0}+++def test_same_thread_followup_migrates_and_delivers_committed_peer_reply(+ tmp_path: Path,+):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.rpc = _PromptRecordingRPC()+ service.runtime.rpc = service.rpc+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Shared context room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )++ service.start()+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops provide the marker", "thread_id": "thread-1"},+ )+ _wait_for(lambda: len(service.rpc.prompts) == 1)+ _wait_for(+ lambda: any(+ event["kind"] == "room.activity"+ and event["payload"]["discussion_event_id"] == "user-1"+ for event in service._events("room-1")+ )+ )+ with sqlite3.connect(db) as conn:+ assert conn.execute(+ """SELECT COUNT(*) FROM hosted_room_policy_transcript+ WHERE room_id='room-1' AND thread_id='thread-1'"""+ ).fetchone()[0] == 2+ conn.execute("DELETE FROM hosted_room_policy_transcript")+ conn.execute(+ """DELETE FROM hosted_room_policy_transcript_state+ WHERE room_id='room-1'"""+ )+ service.send(+ room_id="room-1",+ event_id="user-2",+ payload={"text": "@hermes continue", "thread_id": "thread-1"},+ )+ _wait_for(lambda: len(service.rpc.prompts) == 2)+ assert service.stop(timeout=1.0)++ profile, prompt = service.rpc.prompts[1]+ assert profile == "default"+ assert "@ops: reply from ops" in prompt+ assert "User (user): @hermes continue" in prompt+++def test_active_same_thread_followup_waits_for_current_task(tmp_path: Path):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.rpc = _BlockingFirstRPC()+ service.runtime.rpc = service.rpc+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Serialized room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )++ service.start()+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops start", "thread_id": "thread-1"},+ )+ assert service.rpc.first_started.wait(timeout=2)+ service.send(+ room_id="room-1",+ event_id="user-2",+ payload={"text": "@hermes follow up", "thread_id": "thread-1"},+ )+ assert len(service.rpc.prompts) == 1+ service.rpc.release_first.set()+ _wait_for(lambda: len(service.rpc.prompts) == 2)+ _wait_for(+ lambda: any(+ event["kind"] == "room.activity"+ and event["payload"]["discussion_event_id"] == "user-2"+ for event in service._events("room-1")+ )+ )+ assert service.stop(timeout=1.0)+ assert "User (user): @hermes follow up" in service.rpc.prompts[1][1]+++def test_thread_transcript_prunes_committed_message_and_settlement_together(+ tmp_path: Path,+):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.rpc = _FakeRPC()+ service.runtime.rpc = service.rpc+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Bounded room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ service.start()+ service.send(+ room_id="room-1",+ event_id="user-first",+ payload={"text": "@ops old", "thread_id": "thread-1"},+ )+ _wait_for(+ lambda: any(+ event["kind"] == "room.activity"+ for event in service._events("room-1")+ )+ )+ assert service.stop(timeout=1.0)+ for index in range(24):+ _append_room_event(+ db,+ room_id="room-1",+ event_id=f"user-tail-{index}",+ kind="message.user",+ actor={"kind": "user", "id": "desktop"},+ payload={"text": f"tail {index}", "thread_id": "thread-1"},+ )++ room = hosted_rooms.room_state(db, room_id="room-1")+ snapshot = service._policy_snapshot(room)+ assert len(snapshot.events) == 24+ assert {event["kind"] for event in snapshot.events} == {"message.user"}+ discussion.plan_next_task(+ room,+ snapshot.events,+ local_profiles=service.local_profiles(),+ initial_watermarks=snapshot.watermarks,+ )+++def test_service_uses_low_idle_poll_with_immediate_wakeup(tmp_path: Path):+ service = HostedRoomService(_server(), db_path=tmp_path / "state.db")++ assert service.runtime.poll_interval_seconds == 5.0+ assert service.runtime.active_poll_interval_seconds == 0.25+ assert service.runtime.turn_timeout_seconds == 1830.0+ service.runtime._wake.clear()+ service.wakeup()+ assert service.runtime._wake.is_set()+++def test_service_derives_room_deadline_from_agent_timeout(tmp_path: Path, monkeypatch):+ monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "90")++ service = HostedRoomService(_server(), db_path=tmp_path / "state.db")++ assert service.runtime.turn_timeout_seconds == 120.0+++def test_service_publishes_deferred_turn_continues_and_retries_new_generation(+ tmp_path: Path,+):+ now = [100.0]++ def clock():+ return now[0]++ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ service.rpc = _FakeRPC()+ service.runtime.rpc = service.rpc+ service.runtime.clock = clock+ service.runtime.lease_ttl_seconds = 30+ service.runtime.indeterminate_defer_seconds = 5+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Resilient room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "default"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ service.send(+ room_id="room-1",+ event_id="user-resilience",+ payload={"text": "Check this", "thread_id": "thread-1"},+ )+ first = driver.list_tasks(db, room_id="room-1", status="queued")[0]+ old_lease = driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id=service.bindings()[0].gateway_id,+ authority_epoch=1,+ process_generation="offline-member",+ ttl_seconds=1,+ clock=clock,+ )+ old_attempt = driver.start_task(+ db,+ first["identity"],+ old_lease,+ expected_cancel_generation=0,+ clock=clock,+ )++ now[0] = 102.0+ binding = service.bindings()[0]+ service.runtime._process_room(binding)+ now[0] = 108.0+ service.runtime._process_room(binding)++ events = service._events("room-1")+ deferred = next(event for event in events if event["kind"] == "turn.deferred")+ assert deferred["payload"]["task_id"] == first["identity"].task_id+ assert deferred["payload"]["execution_generation"] == 1+ assert any(+ event["kind"] == "message.member" and event["payload"]["member_id"] == "ops"+ for event in events+ )++ requeued = service.retry_room_task(+ "room-1",+ task_id=first["identity"].task_id,+ )+ assert requeued["status"] == "queued"+ lease = service.runtime._leases["room-1"]+ retried = driver.start_task(+ db,+ first["identity"],+ lease,+ expected_cancel_generation=0,+ clock=clock,+ )+ assert retried.execution_generation == old_attempt.execution_generation + 1+++def test_stop_fence_prevents_the_next_room_member_from_starting(+ tmp_path: Path, monkeypatch+):+ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ monkeypatch.setattr(service, "local_profiles", lambda: ("default", "ops"))+ service.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "Inspect the release", "thread_id": "thread-1"},+ )+ assert len(driver.list_tasks(db, room_id="room-1")) == 1++ assert service.stop_room("room-1", cancel_id="stop-1") == 1+ service.prepare_room(service.bindings()[0])++ tasks = driver.list_tasks(db, room_id="room-1")+ assert len(tasks) == 1+ assert tasks[0]["status"] == "cancelled"+ assert any(+ event["kind"] == "room.stop_requested" for event in service._events("room-1")+ )+++def test_acknowledged_stop_refuses_to_disband_while_exact_turn_is_still_running(+ tmp_path: Path,+):+ class PendingStopRPC(_FakeRPC):+ def __init__(self) -> None:+ super().__init__()+ self.active_task_id = None++ def info(self, *, profile, session_id, source):+ return {"active": True, "task_id": self.active_task_id}++ def interrupt(self, *, profile, session_id, source, expected_task_id):+ return None++ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ rpc = PendingStopRPC()+ service.rpc = rpc+ service.runtime.rpc = rpc+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops inspect", "thread_id": "thread-1"},+ )+ task = driver.list_tasks(db, room_id="room-1", status="queued")[0]+ binding = service.bindings()[0]+ lease = driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id=binding.gateway_id,+ authority_epoch=binding.authority_epoch,+ process_generation="worker",+ ttl_seconds=30,+ clock=time.time,+ )+ driver.start_task(+ db,+ task["identity"],+ lease,+ expected_cancel_generation=0,+ clock=time.time,+ )+ rpc.sessions[("ops", "Group: room-1")] = {"session_id": "ops-session"}+ rpc.active_task_id = task["identity"].task_id++ with pytest.raises(RuntimeError, match="still stopping"):+ service.stop_room(+ "room-1",+ cancel_id="stop-1",+ require_acknowledged=True,+ )++ stopping = driver.get_task(db, task["identity"])+ assert stopping["status"] == "stopping"+ assert stopping["cancel_id"] == "stop-1"+++def test_local_pending_approval_requires_exact_task_generation_and_request(+ tmp_path: Path,+):+ class ApprovalRPC(_FakeRPC):+ def __init__(self) -> None:+ super().__init__()+ self.approvals = []++ def approve(self, *, session_id, request_id, choice):+ self.approvals.append((session_id, request_id, choice))+ return {"resolved": 1}++ db = tmp_path / "state.db"+ service = HostedRoomService(_server(), db_path=db)+ rpc = ApprovalRPC()+ service.rpc = rpc+ service.runtime.rpc = rpc+ service.local_profiles = lambda: ("default", "ops")+ service.create_room(+ room_id="room-1",+ name="Release room",+ members=[+ {"member_id": "default", "profile": "default", "handle": "hermes"},+ {"member_id": "ops", "profile": "ops", "handle": "ops"},+ ],+ )+ service.send(+ room_id="room-1",+ event_id="user-1",+ payload={"text": "@ops inspect", "thread_id": "thread-1"},+ )+ task = driver.list_tasks(db, room_id="room-1", status="queued")[0]+ binding = service.bindings()[0]+ lease = driver.acquire_lease(+ db,+ room_id="room-1",+ gateway_id=binding.gateway_id,+ authority_epoch=binding.authority_epoch,+ process_generation="worker",+ ttl_seconds=30,+ clock=time.time,+ )+ driver.start_task(+ db,+ task["identity"],+ lease,+ expected_cancel_generation=0,+ clock=time.time,+ )+ task = driver.get_task(db, task["identity"])+ service.runtime._report_pending_action(+ task,+ session_id="ops-session",+ info={+ "pending_approval": {+ "request_id": "approval-1",+ "choices": ["once", "always", "deny"],+ }+ },+ )++ action = service.status("room-1")["pending_actions"][0]+ assert action["member_id"] == "ops"+ assert action["approval"]["choices"] == ["once", "deny"]+ with pytest.raises(RuntimeError, match="no longer pending"):+ service.approve_room_task(+ "room-1",+ member_id="ops",+ task_id=task["identity"].task_id,+ execution_generation=1,+ choice="once",+ request_id="wrong-request",+ )++ assert service.approve_room_task(+ "room-1",+ member_id="ops",+ task_id=task["identity"].task_id,+ execution_generation=1,+ choice="once",+ request_id="approval-1",+ ) == {"resolved": 1}+ assert rpc.approvals == [("ops-session", "approval-1", "once")]+ assert service.status("room-1")["pending_actions"] == []diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.pynew file mode 100644index 00000000000..9fdeede8f20--- /dev/null+++ b/tui_gateway/hosted_room_driver.py@@ -0,0 +1,1276 @@+"""Runtime adapter for gateway-owned hosted room turns.++The durable state machine lives in :mod:`gateway.hosted_room_driver`. This+module owns the process-local worker and a deliberately small, injected session+adapter. It does not import the gateway server, construct agents, or depend on+any client transport.++The adapter normalizes existing internal session RPCs into seven methods. A+future server integration can implement those methods with the in-process+handlers while tests use deterministic fakes and no models or network.++One bounded supervisor schedules independent room workers. Profile turn locks+still serialize Bots that share one profile, while a room waiting for approval+cannot stop unrelated rooms from progressing. Hosted member sessions+intentionally reuse ``Group: <room_id>`` so a local-to-hosted migration+preserves the same canonical transcript instead of forking a second conversation.+"""++from __future__ import annotations++import contextlib+import threading+import time+import uuid+from collections.abc import Callable, Iterable, Mapping, Sequence+from dataclasses import dataclass+from pathlib import Path+from typing import Any, ContextManager, Protocol, cast++from gateway import hosted_room_driver as state+++ROOM_SESSION_SOURCE = "bot_room"+MAX_TERMINAL_TEXT_BYTES = 64 * 1024+_TERMINAL_TRUNCATION_NOTICE = (+ "\n\n[Reply truncated. Ask the Bot to share the full result as a file.]"+)+++class InternalSessionRPC(Protocol):+ """Normalized in-process session operations required by the room driver."""++ def resolve_exact(+ self, *, profile: str, title: str, source: str+ ) -> Mapping[str, Any] | None:+ """Return the exact titled session under ``profile``, if it exists."""++ def create(self, *, profile: str, title: str, source: str) -> Mapping[str, Any]:+ """Create a session without model or provider overrides."""++ def resume(+ self, *, profile: str, session_id: str, source: str+ ) -> Mapping[str, Any]:+ """Resume the canonical room session."""++ def submit(+ self,+ *,+ profile: str,+ session_id: str,+ prompt: str,+ source: str,+ task: state.TaskIdentity,+ execution_generation: int,+ on_terminal: Callable[[Mapping[str, Any]], None],+ ) -> Mapping[str, Any]:+ """Submit one fenced room turn and durably report its terminal result."""++ def history(+ self, *, profile: str, session_id: str, source: str+ ) -> Sequence[Mapping[str, Any]]:+ """Return normalized session messages in durable order."""++ def info(self, *, profile: str, session_id: str, source: str) -> Mapping[str, Any]:+ """Return normalized live status for a session."""++ def interrupt(+ self,+ *,+ profile: str,+ session_id: str,+ source: str,+ expected_task_id: str,+ ) -> Mapping[str, Any] | None:+ """Interrupt only when the current turn still matches the expected task."""+++@dataclass(frozen=True)+class HostedRoomBinding:+ """Current server-issued authority coordinate for one hosted room."""++ room_id: str+ gateway_id: str+ authority_epoch: int+++@dataclass(frozen=True)+class _TerminalReceipt:+ status: state.TerminalStatus+ settlement_id: str+ result: dict[str, Any]+++@dataclass(frozen=True)+class _RecoveryInspection:+ terminal: _TerminalReceipt | None+ active: bool+ status: str | None+++class HostedRoomRuntime:+ """Run queued hosted-room tasks independently of Desktop connections."""++ def __init__(+ self,+ *,+ db_path: Path | str,+ rooms: Iterable[HostedRoomBinding] | Callable[[], Iterable[HostedRoomBinding]],+ turn_lock: Callable[[str], ContextManager[Any]],+ rpc: InternalSessionRPC,+ prepare_room: Callable[[HostedRoomBinding], None] | None = None,+ publish_terminal: Callable[[HostedRoomBinding, Mapping[str, Any]], None]+ | None = None,+ pending_action: Callable[[str, str, Mapping[str, Any] | None], None]+ | None = None,+ clock: Callable[[], float] = time.time,+ lease_ttl_seconds: float = 30.0,+ poll_interval_seconds: float = 5.0,+ active_poll_interval_seconds: float = 0.25,+ turn_timeout_seconds: float = 1830.0,+ indeterminate_defer_seconds: float = 60.0,+ max_concurrent_rooms: int = 4,+ process_generation: str | None = None,+ ) -> None:+ if lease_ttl_seconds <= 0:+ raise ValueError("lease_ttl_seconds must be positive")+ if poll_interval_seconds <= 0:+ raise ValueError("poll_interval_seconds must be positive")+ if active_poll_interval_seconds <= 0:+ raise ValueError("active_poll_interval_seconds must be positive")+ if turn_timeout_seconds <= 0:+ raise ValueError("turn_timeout_seconds must be positive")+ if indeterminate_defer_seconds <= 0:+ raise ValueError("indeterminate_defer_seconds must be positive")+ if (+ isinstance(max_concurrent_rooms, bool)+ or not isinstance(max_concurrent_rooms, int)+ or max_concurrent_rooms < 1+ ):+ raise ValueError("max_concurrent_rooms must be a positive integer")+ self.db_path = Path(db_path)+ self.rpc = rpc+ self.turn_lock = turn_lock+ self.prepare_room = prepare_room+ self.publish_terminal = publish_terminal+ self.pending_action = pending_action+ self.clock = clock+ self.lease_ttl_seconds = float(lease_ttl_seconds)+ self.poll_interval_seconds = float(poll_interval_seconds)+ self.active_poll_interval_seconds = float(active_poll_interval_seconds)+ self.turn_timeout_seconds = float(turn_timeout_seconds)+ self.indeterminate_defer_seconds = float(indeterminate_defer_seconds)+ self.max_concurrent_rooms = max_concurrent_rooms+ self.process_generation = process_generation or uuid.uuid4().hex+ self._rooms_provider: Callable[[], Iterable[HostedRoomBinding]]+ if callable(rooms):+ self._rooms_provider = cast(+ Callable[[], Iterable[HostedRoomBinding]], rooms+ )+ else:+ room_bindings = tuple(rooms)+ self._rooms_provider = lambda: room_bindings++ self._stop = threading.Event()+ self._wake = threading.Event()+ self._thread: threading.Thread | None = None+ self._room_threads: dict[str, threading.Thread] = {}+ self._rooms_needing_reschedule: set[str] = set()+ self._leases: dict[str, state.DriverLease] = {}+ self._recovered_leases: set[tuple[str, int]] = set()+ self._inspected_indeterminate_attempts: set[tuple[str, str, int]] = set()+ self._ambiguous_rooms: dict[str, float] = {}+ self._blocked_rooms: set[str] = set()+ self._status_lock = threading.Lock()+ self._current_tasks: dict[str, state.TaskIdentity] = {}+ self._room_schedule_cursor = 0+ self._last_error: str | None = None+ self._cycles = 0++ def start(self) -> None:+ """Start the bounded room-worker supervisor idempotently."""+ with self._status_lock:+ if self._thread is not None and self._thread.is_alive():+ return+ self._stop.clear()+ self._wake.set()+ self._thread = threading.Thread(+ target=self._worker_loop,+ name="hosted-room-driver-supervisor",+ daemon=True,+ )+ self._thread.start()++ def stop(self, *, timeout: float = 5.0) -> bool:+ """Request a bounded clean stop without interrupting accepted turns."""+ self._stop.set()+ self._wake.set()+ with self._status_lock:+ thread = self._thread+ if thread is None:+ return True+ deadline = time.monotonic() + max(0.0, timeout)+ thread.join(max(0.0, deadline - time.monotonic()))+ with self._status_lock:+ room_threads = tuple(self._room_threads.values())+ for room_thread in room_threads:+ room_thread.join(max(0.0, deadline - time.monotonic()))+ return not thread.is_alive() and all(+ not room_thread.is_alive() for room_thread in room_threads+ )++ def wakeup(self) -> None:+ """Wake the worker after task admission or a room-state change."""+ with self._status_lock:+ # If the supervisor observes this signal while a room still owns a+ # worker slot, remember to revisit it once that thread exits. This+ # closes the race between terminal publication/route repair and the+ # longer idle fallback without turning idle rooms into a busy loop.+ self._rooms_needing_reschedule.update(self._room_threads)+ self._wake.set()++ def status(self) -> dict[str, Any]:+ """Return a transport-neutral snapshot of runtime health."""+ with self._status_lock:+ thread = self._thread+ current_tasks = tuple(self._current_tasks.values())+ return {+ "running": bool(thread and thread.is_alive()),+ "stopping": self._stop.is_set(),+ "process_generation": self.process_generation,+ "current_task": current_tasks[0] if current_tasks else None,+ "current_tasks": current_tasks,+ "leased_rooms": tuple(sorted(self._leases)),+ "blocked_rooms": tuple(sorted(self._blocked_rooms)),+ "last_error": self._last_error,+ "cycles": self._cycles,+ }++ def cancel(+ self,+ identity: state.TaskIdentity,+ *,+ cancel_id: str,+ ) -> dict[str, Any]:+ """Persist a stop intent, then commit cancellation after acknowledgement."""+ before = state.get_task(self.db_path, identity)+ if before["status"] in {"queued", "deferred"}:+ cancelled = state.cancel_task(+ self.db_path,+ identity,+ cancel_id=cancel_id,+ expected_cancel_generation=before["cancel_generation"],+ clock=self.clock,+ )+ self.wakeup()+ return cancelled++ stopping = state.begin_task_cancel(+ self.db_path,+ identity,+ cancel_id=cancel_id,+ expected_cancel_generation=before["cancel_generation"],+ clock=self.clock,+ )+ binding = self._binding_for_room(identity.room_id)+ try:+ if binding is not None and self._interrupt_stopping_task(binding, stopping):+ stopping = state.complete_task_cancel(+ self.db_path,+ identity,+ cancel_id=cancel_id,+ expected_cancel_generation=stopping["cancel_generation"],+ clock=self.clock,+ )+ except Exception as exc:+ self._record_error(f"stop remains pending: {exc}")+ stopping = state.get_task(self.db_path, identity)+ self.wakeup()+ return stopping++ def retry_indeterminate(self, identity: state.TaskIdentity) -> dict[str, Any]:+ """Explicitly retry one uncertain attempt under the current room lease."""+ task = state.get_task(self.db_path, identity)+ if task["status"] not in {"indeterminate", "deferred"}:+ raise state.InvalidTaskTransitionError(+ f"cannot retry task in state '{task['status']}'"+ )+ binding = self._binding_for_room(identity.room_id)+ if binding is None:+ raise state.RoomUnavailableError("hosted room is unavailable")+ lease = self._ensure_lease(binding)+ if task["status"] == "deferred":+ retried = state.requeue_deferred_task(+ self.db_path,+ identity,+ lease,+ expected_execution_generation=task["execution_generation"],+ expected_cancel_generation=task["cancel_generation"],+ clock=self.clock,+ )+ with self._status_lock:+ self._blocked_rooms.discard(identity.room_id)+ self.wakeup()+ return retried+ inspection = self._inspect_local_recovery_session(task)+ if inspection.active:+ with self._status_lock:+ self._blocked_rooms.add(identity.room_id)+ raise state.InvalidTaskTransitionError(+ "cannot retry while the original task attempt is still active"+ )+ retried = state.requeue_indeterminate_task(+ self.db_path,+ identity,+ lease,+ expected_execution_generation=task["execution_generation"],+ expected_cancel_generation=task["cancel_generation"],+ clock=self.clock,+ )+ with self._status_lock:+ self._blocked_rooms.discard(identity.room_id)+ self.wakeup()+ return retried++ def _interrupt_stopping_task(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ ) -> bool:+ transport = self.rpc+ if transport is None:+ return False+ profile = task["payload"]["target_profile"]+ session = transport.resolve_exact(+ profile=profile,+ title=room_session_title(binding.room_id),+ source=ROOM_SESSION_SOURCE,+ )+ if session is None:+ # A local accepted turn cannot survive without its canonical+ # session. Resolution errors raise; an authoritative absence is a+ # safe Stop acknowledgement.+ return True+ resumed = transport.resume(+ profile=profile,+ session_id=_session_id(session),+ source=ROOM_SESSION_SOURCE,+ )+ session_id = _session_id(resumed)+ info = transport.info(+ profile=profile,+ session_id=session_id,+ source=ROOM_SESSION_SOURCE,+ )+ active = bool(info.get("active", info.get("running", False)))+ if not active:+ # History was checked immediately before this probe. An exact+ # local session that is no longer active cannot keep executing, and+ # after a restart its process-local task marker is expected to be+ # absent.+ return True+ if not _info_is_active_for(info, task["identity"], require_exact=True):+ return False+ result = transport.interrupt(+ profile=profile,+ session_id=session_id,+ source=ROOM_SESSION_SOURCE,+ expected_task_id=task["identity"].task_id,+ )+ if result is None:+ return False+ return result.get("interrupted") is True or str(result.get("status") or "") in {+ "cancelled",+ "interrupted",+ "stopping",+ }++ def _settle_stopping_completion(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ lease: state.DriverLease,+ ) -> bool:+ """Publish a terminal receipt that arrived before Stop was acknowledged."""+ transport = self.rpc+ if transport is None:+ return False+ profile = task["payload"]["target_profile"]+ session = transport.resolve_exact(+ profile=profile,+ title=room_session_title(binding.room_id),+ source=ROOM_SESSION_SOURCE,+ )+ if session is None:+ return False+ resumed = transport.resume(+ profile=profile,+ session_id=_session_id(session),+ source=ROOM_SESSION_SOURCE,+ )+ receipt = _find_terminal_receipt(+ transport.history(+ profile=profile,+ session_id=_session_id(resumed),+ source=ROOM_SESSION_SOURCE,+ ),+ task["identity"],+ int(task["execution_generation"]),+ )+ if receipt is None:+ return False+ settled = state.settle_stopping_task(+ self.db_path,+ task["identity"],+ lease,+ expected_execution_generation=int(task["execution_generation"]),+ expected_cancel_generation=int(task["cancel_generation"]),+ settlement_id=receipt.settlement_id,+ status=receipt.status,+ result=receipt.result,+ clock=self.clock,+ )+ if self.publish_terminal is not None:+ self.publish_terminal(binding, settled)+ return True++ def _report_pending_action(+ self,+ task: Mapping[str, Any],+ *,+ session_id: str,+ info: Mapping[str, Any],+ ) -> None:+ if self.pending_action is None:+ return+ payload = task.get("payload") or {}+ member_id = str(+ payload.get("target_member_id") or payload.get("target_profile") or ""+ )+ approval = info.get("pending_approval") or info.get("approval")+ action = None+ if isinstance(approval, Mapping):+ safe_approval = dict(approval)+ choices = [+ choice+ for choice in safe_approval.get("choices") or ()+ if choice in {"once", "deny"}+ ]+ safe_approval["choices"] = choices or ["once", "deny"]+ action = {+ "kind": "approval",+ "task_id": task["identity"].task_id,+ "execution_generation": int(task["execution_generation"]),+ "run_id": info.get("run_id"),+ "session_id": session_id,+ "request_id": safe_approval.get("request_id"),+ "approval": safe_approval,+ }+ self.pending_action(task["identity"].room_id, member_id, action)++ def _retry_stopping_tasks(+ self, binding: HostedRoomBinding, lease: state.DriverLease+ ) -> bool:+ pending = state.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status="stopping",+ )+ for task in pending:+ try:+ lease = self._renew_lease_if_needed(binding, lease)+ if self._settle_stopping_completion(binding, task, lease):+ continue+ if not self._interrupt_stopping_task(binding, task):+ return True+ self._complete_acknowledged_stop(binding, task, lease)+ except Exception as exc:+ self._record_error(f"stop retry remains pending: {exc}")+ return True+ return False++ def _worker_loop(self) -> None:+ try:+ while not self._stop.is_set():+ # Clear before work so a write racing the cycle remains set and+ # causes an immediate follow-up pass rather than being lost.+ self._wake.clear()+ try:+ self._run_cycle()+ except Exception as exc: # keep independent rooms serviceable+ self._record_error(f"worker cycle failed: {exc}")+ with self._status_lock:+ self._cycles += 1+ self._wake.wait(self.poll_interval_seconds)+ finally:+ while True:+ with self._status_lock:+ room_threads = tuple(+ thread+ for thread in self._room_threads.values()+ if thread.is_alive()+ )+ if not room_threads:+ break+ for room_thread in room_threads:+ room_thread.join(self.active_poll_interval_seconds)+ self._release_idle_leases()++ def _run_cycle(self) -> None:+ with self._status_lock:+ supervisor = self._thread+ if threading.current_thread() is not supervisor:+ for binding in tuple(self._rooms_provider()):+ if self._stop.is_set():+ return+ self._run_room_once(binding)+ return++ with self._status_lock:+ self._room_threads = {+ room_id: thread+ for room_id, thread in self._room_threads.items()+ if thread.is_alive()+ }+ available = self.max_concurrent_rooms - len(self._room_threads)+ active_rooms = set(self._room_threads)+ if available <= 0:+ return++ bindings = tuple(self._rooms_provider())+ if not bindings:+ return+ start = self._room_schedule_cursor % len(bindings)+ ordered_bindings = bindings[start:] + bindings[:start]+ self._room_schedule_cursor = (start + 1) % len(bindings)++ for binding in ordered_bindings:+ if self._stop.is_set() or available <= 0:+ return+ if binding.room_id in active_rooms:+ continue+ room_thread = threading.Thread(+ target=self._run_room_once,+ args=(binding,),+ name=f"hosted-room-{binding.room_id[:24]}",+ daemon=True,+ )+ with self._status_lock:+ self._room_threads[binding.room_id] = room_thread+ active_rooms.add(binding.room_id)+ available -= 1+ room_thread.start()++ def _run_room_once(self, binding: HostedRoomBinding) -> None:+ try:+ self._process_room(binding)+ except state.LeaseHeldError:+ return+ except (state.RoomUnavailableError, state.StaleLeaseError) as exc:+ self._drop_lease(binding.room_id)+ with self._status_lock:+ self._blocked_rooms.discard(binding.room_id)+ self._record_error(f"room {binding.room_id}: {exc}")+ except Exception as exc:+ self._record_error(f"room {binding.room_id}: {exc}")+ finally:+ current = threading.current_thread()+ with self._status_lock:+ if self._room_threads.get(binding.room_id) is current:+ self._room_threads.pop(binding.room_id, None)+ should_wake = binding.room_id in self._rooms_needing_reschedule+ self._rooms_needing_reschedule.discard(binding.room_id)+ if should_wake:+ self.wakeup()++ def _process_room(self, binding: HostedRoomBinding) -> None:+ if self.prepare_room is not None:+ self.prepare_room(binding)+ self._inspect_abandoned_attempts(binding)+ deferred_until = self._ambiguous_rooms.get(binding.room_id)+ if deferred_until is not None:+ running = state.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status="running",+ )+ if not running:+ self._ambiguous_rooms.pop(binding.room_id, None)+ elif self.clock() < deferred_until:+ return+ else:+ self._ambiguous_rooms.pop(binding.room_id, None)+ lease = self._ensure_lease(binding)+ recovery_key = (lease.room_id, lease.lease_generation)+ if recovery_key not in self._recovered_leases:+ state.recover_room(self.db_path, lease, clock=self.clock)+ self._recovered_leases.add(recovery_key)+ if self._retry_stopping_tasks(binding, lease):+ with self._status_lock:+ self._blocked_rooms.add(binding.room_id)+ return+ if self._reconcile_indeterminate(binding, lease):+ return++ queued = state.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status="queued",+ )+ for task in queued:+ if self._stop.is_set():+ return+ lease = self._renew_lease_if_needed(binding, lease)+ attempt = state.start_task(+ self.db_path,+ task["identity"],+ lease,+ expected_cancel_generation=task["cancel_generation"],+ clock=self.clock,+ )+ self._execute_attempt(binding, task, attempt)++ def _ensure_lease(self, binding: HostedRoomBinding) -> state.DriverLease:+ with self._status_lock:+ current = self._leases.get(binding.room_id)+ if current is not None:+ try:+ renewed = self._renew_lease_if_needed(binding, current)+ except state.StaleLeaseError:+ self._drop_lease(binding.room_id)+ else:+ return renewed++ lease = state.acquire_lease(+ self.db_path,+ room_id=binding.room_id,+ gateway_id=binding.gateway_id,+ authority_epoch=binding.authority_epoch,+ process_generation=self.process_generation,+ ttl_seconds=self.lease_ttl_seconds,+ clock=self.clock,+ )+ with self._status_lock:+ self._leases[binding.room_id] = lease+ self._recovered_leases = {+ key for key in self._recovered_leases if key[0] != binding.room_id+ }+ return lease++ def _renew_lease_if_needed(+ self,+ binding: HostedRoomBinding,+ lease: state.DriverLease,+ *,+ force: bool = False,+ ) -> state.DriverLease:+ del binding+ renew_at = lease.expires_at - (self.lease_ttl_seconds / 2)+ if not force and self.clock() < renew_at:+ return lease+ renewed = state.renew_lease(+ self.db_path,+ lease,+ ttl_seconds=self.lease_ttl_seconds,+ clock=self.clock,+ )+ with self._status_lock:+ self._leases[lease.room_id] = renewed+ return renewed++ def _execute_attempt(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ attempt: state.TaskAttempt,+ ) -> None:+ profile = task["payload"]["target_profile"]+ transport = self.rpc+ submit_attempted = False+ with self._status_lock:+ self._current_tasks[binding.room_id] = attempt.identity+ try:+ with self.turn_lock(profile):+ session = self._resolve_or_create(transport, profile, binding.room_id)+ # An in-process submit should fail before admission or return+ # after it, but an unexpected exception at that boundary is+ # still ambiguous. Never terminalize it as a proven failure.+ submit_attempted = True++ def on_terminal(receipt: Mapping[str, Any]) -> None:+ status = receipt.get("status")+ if status == "cancelled":+ self.wakeup()+ return+ terminal_status: state.TerminalStatus = (+ "settled" if status == "settled" else "failed"+ )+ try:+ settled = state.settle_task(+ self.db_path,+ attempt,+ settlement_id=(+ receipt.get("settlement_id")+ or f"reply:{attempt.identity.task_id}:{attempt.execution_generation}"+ ),+ status=terminal_status,+ result=_bounded_terminal_result(receipt),+ clock=self.clock,+ )+ if self.publish_terminal is not None:+ self.publish_terminal(binding, settled)+ except state.StaleTaskError:+ try:+ current = state.get_task(self.db_path, attempt.identity)+ if current["status"] == "stopping":+ settled = state.settle_stopping_task(+ self.db_path,+ attempt.identity,+ attempt.lease,+ expected_execution_generation=attempt.execution_generation,+ expected_cancel_generation=int(+ current["cancel_generation"]+ ),+ settlement_id=(+ receipt.get("settlement_id")+ or f"reply:{attempt.identity.task_id}:{attempt.execution_generation}"+ ),+ status=terminal_status,+ result=_bounded_terminal_result(receipt),+ clock=self.clock,+ )+ if self.publish_terminal is not None:+ self.publish_terminal(binding, settled)+ except (state.StaleLeaseError, state.StaleTaskError):+ pass+ except state.StaleLeaseError:+ # Cancellation, disband, or authority transfer won the+ # durable race. The model result is intentionally+ # discarded; never turn a correct fence into a worker+ # thread exception.+ pass+ except state.DriverStateError as exc:+ # A malformed terminal receipt must not escape the+ # callback and hold the profile lock until the deadline.+ self._settle_failure_if_current(+ attempt,+ RuntimeError(+ f"terminal result could not be committed: {exc}"+ ),+ )+ self.wakeup()++ deadline_monotonic = time.monotonic() + self.turn_timeout_seconds+ transport.submit(+ profile=profile,+ session_id=_session_id(session),+ prompt=task["payload"]["prompt"],+ source=ROOM_SESSION_SOURCE,+ task=attempt.identity,+ execution_generation=attempt.execution_generation,+ on_terminal=on_terminal,+ )+ receipt = self._wait_for_terminal(+ binding,+ task=task,+ profile=profile,+ session_id=_session_id(session),+ attempt=attempt,+ transport=transport,+ deadline_monotonic=deadline_monotonic,+ )+ if receipt is None:+ return+ state.settle_task(+ self.db_path,+ attempt,+ settlement_id=receipt.settlement_id,+ status=receipt.status,+ result=receipt.result,+ clock=self.clock,+ )+ except (state.StaleLeaseError, state.StaleTaskError) as exc:+ self._drop_lease(binding.room_id)+ self._record_error(f"task {attempt.identity.task_id} fenced: {exc}")+ except Exception as exc:+ if submit_attempted:+ self._drop_lease(binding.room_id)+ self._ambiguous_rooms[binding.room_id] = attempt.lease.expires_at+ self._record_error(+ f"task {attempt.identity.task_id} observation failed after submit: {exc}"+ )+ else:+ self._settle_failure_if_current(attempt, exc)+ finally:+ with self._status_lock:+ self._current_tasks.pop(binding.room_id, None)+ # The task may have published a reply, deferred a member, or+ # exposed the next turn while this room thread still occupied+ # its slot. Schedule exactly one immediate follow-up after the+ # thread leaves; idle room scans never set this marker.+ self._rooms_needing_reschedule.add(binding.room_id)++ def _wait_for_terminal(+ self,+ binding: HostedRoomBinding,+ *,+ task: Mapping[str, Any],+ profile: str,+ session_id: str,+ attempt: state.TaskAttempt,+ transport: InternalSessionRPC,+ deadline_monotonic: float,+ ) -> _TerminalReceipt | None:+ lease = attempt.lease+ while not self._stop.is_set():+ task = state.get_task(self.db_path, attempt.identity)+ if task["status"] in state.TERMINAL_STATUSES:+ return None+ if task["status"] == "stopping":+ try:+ lease = self._renew_lease_if_needed(binding, lease)+ if self._settle_stopping_completion(binding, task, lease):+ return None+ if self._interrupt_stopping_task(binding, task):+ self._complete_acknowledged_stop(binding, task, lease)+ return None+ except Exception as exc:+ self._record_error(f"stop retry remains pending: {exc}")+ self._wake.wait(self.active_poll_interval_seconds)+ self._wake.clear()+ continue++ if time.monotonic() >= deadline_monotonic:+ self._expire_attempt_deadline(binding, task, lease)+ return None++ lease = self._renew_lease_if_needed(binding, lease)+ receipt = _find_terminal_receipt(+ transport.history(+ profile=profile,+ session_id=session_id,+ source=ROOM_SESSION_SOURCE,+ ),+ attempt.identity,+ attempt.execution_generation,+ )+ if receipt is not None:+ return receipt++ info = transport.info(+ profile=profile,+ session_id=session_id,+ source=ROOM_SESSION_SOURCE,+ )+ self._report_pending_action(task, session_id=session_id, info=info)+ remaining = max(0.0, deadline_monotonic - time.monotonic())+ self._wake.wait(min(self.active_poll_interval_seconds, remaining))+ self._wake.clear()+ return None++ @staticmethod+ def _deadline_cancel_id(task: Mapping[str, Any]) -> str:+ return f"deadline:{int(task['execution_generation'])}"++ @staticmethod+ def _is_deadline_stop(task: Mapping[str, Any]) -> bool:+ return str(task.get("cancel_id") or "").startswith("deadline:")++ def _settle_deadline_failure(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ lease: state.DriverLease,+ ) -> dict[str, Any]:+ """Publish the explicit terminal outcome after exact Stop acknowledgement."""++ execution_generation = int(task["execution_generation"])+ settled = state.settle_stopping_task(+ self.db_path,+ task["identity"],+ lease,+ expected_execution_generation=execution_generation,+ expected_cancel_generation=int(task["cancel_generation"]),+ settlement_id=f"deadline:{execution_generation}",+ status="failed",+ result={+ "error": (+ "This Group Chat turn exceeded its configured time limit and "+ "was stopped."+ ),+ "reason_code": "turn_deadline_exceeded",+ "timeout_seconds": self.turn_timeout_seconds,+ },+ clock=self.clock,+ )+ if self.publish_terminal is not None:+ self.publish_terminal(binding, settled)+ return settled++ def _complete_acknowledged_stop(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ lease: state.DriverLease,+ ) -> dict[str, Any]:+ if self._is_deadline_stop(task):+ return self._settle_deadline_failure(binding, task, lease)+ return state.complete_task_cancel(+ self.db_path,+ task["identity"],+ cancel_id=task["cancel_id"],+ expected_cancel_generation=task["cancel_generation"],+ clock=self.clock,+ )++ def _expire_attempt_deadline(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ lease: state.DriverLease,+ ) -> None:+ """Fence, stop, and terminalize one exact attempt at its deadline."""++ if task["status"] == "running":+ task = state.begin_task_cancel(+ self.db_path,+ task["identity"],+ cancel_id=self._deadline_cancel_id(task),+ expected_cancel_generation=int(task["cancel_generation"]),+ clock=self.clock,+ )+ elif task["status"] != "stopping":+ return++ # A user Stop that won the race keeps its own cancellation semantics.+ if not self._is_deadline_stop(task):+ return+ lease = self._renew_lease_if_needed(binding, lease, force=True)+ if self._settle_stopping_completion(binding, task, lease):+ return+ if self._interrupt_stopping_task(binding, task):+ self._complete_acknowledged_stop(binding, task, lease)+ return+ self._record_error(+ f"task {task['identity'].task_id} exceeded its deadline; stop remains pending"+ )++ def _inspect_abandoned_attempts(self, binding: HostedRoomBinding) -> None:+ running = state.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status="running",+ )+ for task in running:+ if task["run_process_generation"] == self.process_generation:+ continue+ inspection = self._inspect_local_recovery_session(task)+ if inspection.terminal is not None:+ self._harvest_previous_attempt(binding, task, inspection.terminal)+ elif inspection.active:+ # The prior session still owns the turn. Do not contend for its+ # lease or submit a duplicate prompt.+ raise state.LeaseHeldError("recovered session turn is still active")++ def _inspect_local_recovery_session(+ self,+ task: Mapping[str, Any],+ ) -> _RecoveryInspection:+ """Check only live process state before explicit local recovery.++ A restart loses the in-process terminal callback identity. The ordinary+ session history is a display projection and cannot prove which durable+ task attempt authored a row, so never hydrate or infer completion from+ it. An inactive abandoned attempt remains indeterminate until the user+ explicitly retries it under a new fenced generation.+ """++ profile = task["payload"]["target_profile"]+ with self.turn_lock(profile):+ session = self.rpc.resolve_exact(+ profile=profile,+ title=room_session_title(task["identity"].room_id),+ source=ROOM_SESSION_SOURCE,+ )+ if session is None:+ return _RecoveryInspection(terminal=None, active=False, status=None)+ session_id = _session_id(session)+ info = self.rpc.info(+ profile=profile,+ session_id=session_id,+ source=ROOM_SESSION_SOURCE,+ )+ self._report_pending_action(task, session_id=session_id, info=info)+ return _RecoveryInspection(+ terminal=None,+ active=_info_is_active_for(info, task["identity"]),+ status=str(info.get("status") or "") or None,+ )++ def _reconcile_indeterminate(+ self,+ binding: HostedRoomBinding,+ lease: state.DriverLease,+ ) -> bool:+ unresolved = state.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status="indeterminate",+ )+ if not unresolved:+ with self._status_lock:+ self._blocked_rooms.discard(binding.room_id)+ return False+ for task in unresolved:+ generation = int(task["execution_generation"])+ attempt_key = (+ binding.room_id,+ task["identity"].task_id,+ generation,+ )+ if attempt_key not in self._inspected_indeterminate_attempts:+ inspection = self._inspect_local_recovery_session(task)+ self._inspected_indeterminate_attempts.add(attempt_key)+ if inspection.terminal is not None:+ resolved = state.resolve_indeterminate_task(+ self.db_path,+ task["identity"],+ lease,+ expected_execution_generation=generation,+ expected_cancel_generation=task["cancel_generation"],+ settlement_id=inspection.terminal.settlement_id,+ status=inspection.terminal.status,+ result=inspection.terminal.result,+ clock=self.clock,+ )+ self._inspected_indeterminate_attempts.discard(attempt_key)+ if self.publish_terminal is not None:+ self.publish_terminal(binding, resolved)+ continue+ if inspection.active:+ with self._status_lock:+ self._blocked_rooms.add(binding.room_id)+ return True+ deferred_at = float(+ task.get("indeterminate_at")+ or task.get("updated_at")+ or task.get("created_at")+ or self.clock()+ )+ if self.clock() < deferred_at + self.indeterminate_defer_seconds:+ with self._status_lock:+ self._blocked_rooms.add(binding.room_id)+ return True+ deferred = state.defer_indeterminate_task(+ self.db_path,+ task["identity"],+ lease,+ expected_execution_generation=task["execution_generation"],+ expected_cancel_generation=task["cancel_generation"],+ reason="member_unavailable",+ clock=self.clock,+ )+ self._report_pending_action(task, session_id="", info={})+ if self.publish_terminal is not None:+ self.publish_terminal(binding, deferred)+ with self._status_lock:+ self._blocked_rooms.discard(binding.room_id)+ return False++ def _harvest_previous_attempt(+ self,+ binding: HostedRoomBinding,+ task: Mapping[str, Any],+ receipt: _TerminalReceipt,+ ) -> None:+ previous_lease = state.DriverLease(+ room_id=binding.room_id,+ gateway_id=task["run_gateway_id"],+ authority_epoch=binding.authority_epoch,+ process_generation=task["run_process_generation"],+ lease_generation=task["run_lease_generation"],+ expires_at=0.0,+ )+ previous_attempt = state.TaskAttempt(+ identity=task["identity"],+ lease=previous_lease,+ execution_generation=task["execution_generation"],+ cancel_generation=task["cancel_generation"],+ )+ try:+ state.settle_task(+ self.db_path,+ previous_attempt,+ settlement_id=receipt.settlement_id,+ status=receipt.status,+ result=receipt.result,+ clock=self.clock,+ )+ except (state.StaleLeaseError, state.StaleTaskError):+ # Once the previous proof has expired, the current state contract+ # deliberately offers no unsafe "trust this historical output"+ # escape hatch. The subsequent fenced recovery leaves it+ # indeterminate for explicit user action.+ return++ def _binding_for_room(self, room_id: str) -> HostedRoomBinding | None:+ return next(+ (+ binding+ for binding in self._rooms_provider()+ if binding.room_id == room_id+ ),+ None,+ )++ def _resolve_or_create(+ self,+ transport: InternalSessionRPC,+ profile: str,+ room_id: str,+ ) -> Mapping[str, Any]:+ title = room_session_title(room_id)+ session = transport.resolve_exact(+ profile=profile,+ title=title,+ source=ROOM_SESSION_SOURCE,+ )+ if session is None:+ return transport.create(+ profile=profile,+ title=title,+ source=ROOM_SESSION_SOURCE,+ )+ return transport.resume(+ profile=profile,+ session_id=_session_id(session),+ source=ROOM_SESSION_SOURCE,+ )++ def _settle_failure_if_current(+ self, attempt: state.TaskAttempt, exc: Exception+ ) -> None:+ try:+ state.settle_task(+ self.db_path,+ attempt,+ settlement_id=f"failure:{attempt.identity.task_id}:{attempt.execution_generation}",+ status="failed",+ result={"error": str(exc)},+ clock=self.clock,+ )+ except (state.DriverStateError, state.RoomUnavailableError):+ pass+ self._record_error(f"task {attempt.identity.task_id} failed: {exc}")++ def _record_error(self, message: str) -> None:+ with self._status_lock:+ self._last_error = message++ def _drop_lease(self, room_id: str) -> None:+ with self._status_lock:+ self._leases.pop(room_id, None)++ def _release_idle_leases(self) -> None:+ for room_id, lease in tuple(self._leases.items()):+ try:+ state.release_lease(self.db_path, lease, clock=self.clock)+ except state.DriverStateError:+ continue+ self._drop_lease(room_id)+++def room_session_title(room_id: str) -> str:+ """Return the canonical hidden session title for one hosted room."""+ return f"Group: {room_id}"+++def _session_id(session: Mapping[str, Any]) -> str:+ value = session.get("session_id", session.get("id"))+ if not isinstance(value, str) or not value:+ raise ValueError("session adapter returned no session_id")+ return value+++def _truncate_utf8(value: Any, *, max_bytes: int) -> tuple[str, bool]:+ text = str(value or "")+ encoded = text.encode("utf-8")+ if len(encoded) <= max_bytes:+ return text, False+ suffix = _TERMINAL_TRUNCATION_NOTICE.encode("utf-8")+ prefix = encoded[: max(0, max_bytes - len(suffix))]+ while prefix:+ try:+ return prefix.decode("utf-8") + _TERMINAL_TRUNCATION_NOTICE, True+ except UnicodeDecodeError:+ prefix = prefix[:-1]+ return _TERMINAL_TRUNCATION_NOTICE.strip(), True+++def _bounded_terminal_result(receipt: Mapping[str, Any]) -> dict[str, Any]:+ text, truncated = _truncate_utf8(+ receipt.get("text", ""),+ max_bytes=MAX_TERMINAL_TEXT_BYTES,+ )+ error, error_truncated = _truncate_utf8(+ receipt.get("error", ""),+ max_bytes=4096,+ )+ return {+ "message_id": receipt.get("message_id"),+ "text": text,+ **({"error": error} if error else {}),+ **({"truncated": True} if truncated or error_truncated else {}),+ }+++def _find_terminal_receipt(+ history: Sequence[Mapping[str, Any]],+ identity: state.TaskIdentity,+ execution_generation: int,+) -> _TerminalReceipt | None:+ for message in reversed(history):+ if message.get("task_id") != identity.task_id:+ continue+ if message.get("execution_generation") != execution_generation:+ continue+ if message.get("role") != "assistant":+ continue+ status = message.get("status")+ if status not in {"settled", "failed"}:+ continue+ terminal_status = cast(state.TerminalStatus, status)+ receipt_id = message.get("message_id")+ if not isinstance(receipt_id, str) or not receipt_id:+ receipt_id = f"reply:{identity.task_id}:{execution_generation}"+ return _TerminalReceipt(+ status=terminal_status,+ settlement_id=receipt_id,+ result=_bounded_terminal_result(+ {+ "message_id": receipt_id,+ "text": message.get("content", ""),+ }+ ),+ )+ return None+++def _info_is_active_for(+ info: Mapping[str, Any],+ identity: state.TaskIdentity,+ *,+ require_exact: bool = False,+) -> bool:+ if not bool(info.get("active", info.get("running", False))):+ return False+ active_task_id = info.get("task_id")+ if require_exact:+ return active_task_id == identity.task_id+ return active_task_id in {None, identity.task_id}+++def null_turn_lock(_profile: str) -> Any:+ """Provide an explicit no-op lock for narrow embedding tests."""+ yielddiff --git a/tui_gateway/hosted_room_server_rpc.py b/tui_gateway/hosted_room_server_rpc.pynew file mode 100644index 00000000000..a28dcd65a18--- /dev/null+++ b/tui_gateway/hosted_room_server_rpc.py@@ -0,0 +1,213 @@+"""In-process session adapter for the hosted room driver.++The room worker must not depend on a Desktop/WebSocket transport, but it should+still use the same session handlers as every other TUI/Desktop turn. This+adapter calls the installed handler registry directly and keeps the extra+task proof as an in-process-only Python object that JSON clients cannot forge.+"""++from __future__ import annotations++import itertools+import threading+from collections.abc import Mapping, Sequence+from types import ModuleType+from typing import Any, Callable++from gateway import hosted_room_driver as state+++class HostedRoomSessionError(RuntimeError):+ """Raised when an in-process session operation is rejected."""++ def __init__(self, method: str, code: int, message: str) -> None:+ super().__init__(f"{method} failed: {message}")+ self.method = method+ self.code = code+++class HostedRoomServerRPC:+ """Normalize the installed server handlers for :class:`HostedRoomRuntime`."""++ def __init__(self, server: ModuleType) -> None:+ self.server = server+ self._ids = itertools.count(1)++ def _call(self, method: str, params: dict[str, Any]) -> dict[str, Any]:+ handler = self.server._methods[method]+ envelope = handler(f"hosted-room-{next(self._ids)}", params)+ error = envelope.get("error") if isinstance(envelope, dict) else None+ if isinstance(error, dict):+ raise HostedRoomSessionError(+ method,+ int(error.get("code") or 5000),+ str(error.get("message") or "gateway rejected the request"),+ )+ result = envelope.get("result") if isinstance(envelope, dict) else None+ if not isinstance(result, dict):+ raise HostedRoomSessionError(method, 5000, "gateway returned no result")+ return result++ def resolve_exact(+ self, *, profile: str, title: str, source: str+ ) -> Mapping[str, Any] | None:+ del source+ result = self._call(+ "session.list",+ {"profile": profile, "title": title, "include_hidden": True},+ )+ rows = result.get("sessions")+ if not isinstance(rows, list) or not rows:+ return None+ row = rows[0]+ if not isinstance(row, dict):+ return None+ session_id = row.get("resolved_id") or row.get("id")+ return {"session_id": session_id, "title": row.get("title") or title}++ def create(self, *, profile: str, title: str, source: str) -> Mapping[str, Any]:+ return self._call(+ "session.create",+ {+ "profile": profile,+ "title": title,+ "source": source,+ "hidden": True,+ "room_plumbing": True,+ "follow_profile_config": True,+ "close_on_disconnect": False,+ },+ )++ def resume(+ self, *, profile: str, session_id: str, source: str+ ) -> Mapping[str, Any]:+ return self._call(+ "session.resume",+ {+ "profile": profile,+ "session_id": session_id,+ "omit_messages": True,+ "source": source,+ },+ )++ def submit(+ self,+ *,+ profile: str,+ session_id: str,+ prompt: str,+ source: str,+ task: state.TaskIdentity,+ execution_generation: int,+ on_terminal: Callable[[Mapping[str, Any]], None],+ ) -> Mapping[str, Any]:+ try:+ return self._call(+ "prompt.submit",+ {+ "profile": profile,+ "session_id": session_id,+ "text": prompt,+ "source": source,+ "_hosted_task": {+ "room_id": task.room_id,+ "task_id": task.task_id,+ "thread_id": task.thread_id,+ "turn_id": task.turn_id,+ "execution_generation": execution_generation,+ },+ "_hosted_terminal_callback": on_terminal,+ },+ )+ except HostedRoomSessionError as exc:+ # In-process prompt.submit error envelopes are returned before the+ # background turn is admitted. Preserve that proof so the driver+ # can defer or requeue without waiting out an ambiguity lease.+ exc.not_admitted = True+ raise++ def history(+ self, *, profile: str, session_id: str, source: str+ ) -> Sequence[Mapping[str, Any]]:+ del source+ result = self._call(+ "session.history",+ {"profile": profile, "session_id": session_id},+ )+ rows = result.get("messages")+ return tuple(row for row in rows if isinstance(row, dict)) if isinstance(rows, list) else ()++ def _session_record(self, session_id: str) -> dict[str, Any] | None:+ with self.server._sessions_lock:+ record = self.server._sessions.get(session_id)+ if record is not None:+ return record+ for candidate in self.server._sessions.values():+ if str(candidate.get("session_key") or "") == session_id:+ return candidate+ return None++ def info(self, *, profile: str, session_id: str, source: str) -> Mapping[str, Any]:+ del profile, source+ record = self._session_record(session_id)+ if record is None:+ return {"active": False, "task_id": None}+ lock = record.get("history_lock")+ if not isinstance(lock, type(threading.Lock())):+ return {"active": bool(record.get("running")), "task_id": None}+ with lock:+ task = record.get("_hosted_room_task")+ result = {+ "active": bool(record.get("running")),+ "task_id": task.get("task_id") if isinstance(task, dict) else None,+ }+ pending_reader = getattr(+ self.server, "_pending_approval_request_payload", None+ )+ pending = (+ pending_reader(str(record.get("session_key") or ""))+ if callable(pending_reader)+ else None+ )+ if pending:+ result["status"] = "waiting_for_approval"+ result["pending_approval"] = pending+ return result++ def approve(+ self,+ *,+ session_id: str,+ request_id: str,+ choice: str,+ ) -> Mapping[str, Any]:+ """Resolve one exact local room approval without broad policy changes."""+ return self._call(+ "approval.respond",+ {+ "session_id": session_id,+ "request_id": request_id,+ "choice": choice,+ "all": False,+ },+ )++ def interrupt(+ self,+ *,+ profile: str,+ session_id: str,+ source: str,+ expected_task_id: str,+ ) -> Mapping[str, Any] | None:+ del source+ return self._call(+ "session.interrupt",+ {+ "profile": profile,+ "session_id": session_id,+ "expected_hosted_task_id": expected_task_id,+ },+ )diff --git a/tui_gateway/hosted_room_service.py b/tui_gateway/hosted_room_service.pynew file mode 100644index 00000000000..49dba1d2c68--- /dev/null+++ b/tui_gateway/hosted_room_service.py@@ -0,0 +1,518 @@+"""Production coordinator for same-gateway hosted Discussion rooms."""++from __future__ import annotations++import contextlib+import os+import threading+import time+from collections import Counter+from collections.abc import Iterator, Mapping+from pathlib import Path+from types import ModuleType+from typing import Any++from gateway import hosted_room_discussion as discussion+from gateway import hosted_room_driver as driver+from gateway import hosted_rooms+from gateway.hosted_room_policy_checkpoint import (+ HostedRoomPolicyCheckpoint,+ PolicySnapshot,+)+from tui_gateway.hosted_room_driver import HostedRoomBinding, HostedRoomRuntime+from tui_gateway.hosted_room_server_rpc import HostedRoomServerRPC+++_HOSTED_ROOM_IDLE_FALLBACK_SECONDS = 5.0+_HOSTED_ROOM_ACTIVE_POLL_SECONDS = 0.25+_HOSTED_ROOM_TERMINAL_GRACE_SECONDS = 30.0+++def _hosted_room_turn_timeout_seconds() -> float:+ try:+ agent_timeout = float(os.getenv("HERMES_AGENT_TIMEOUT", "1800"))+ except (TypeError, ValueError):+ agent_timeout = 1800.0+ if agent_timeout <= 0:+ agent_timeout = 1800.0+ return agent_timeout + _HOSTED_ROOM_TERMINAL_GRACE_SECONDS+++class HostedRoomService:+ """Own the hosted Discussion policy and its transport-free worker."""++ def __init__(+ self, server: ModuleType, *, db_path: Path | str | None = None+ ) -> None:+ self.server = server+ self.db_path = Path(db_path or hosted_rooms.default_db_path())+ hosted_rooms.prune_disbanded_rooms(self.db_path)+ self._policy_lock = threading.RLock()+ self._pending_actions: dict[tuple[str, str], dict[str, Any]] = {}+ self.policy_checkpoint = HostedRoomPolicyCheckpoint(self.db_path)+ self.rpc = HostedRoomServerRPC(server)+ self.runtime = HostedRoomRuntime(+ db_path=self.db_path,+ rooms=self.bindings,+ rpc=self.rpc,+ turn_lock=self._turn_lock,+ prepare_room=self.prepare_room,+ publish_terminal=self.publish_terminal,+ pending_action=self._set_pending_action,+ poll_interval_seconds=_HOSTED_ROOM_IDLE_FALLBACK_SECONDS,+ active_poll_interval_seconds=_HOSTED_ROOM_ACTIVE_POLL_SECONDS,+ turn_timeout_seconds=_hosted_room_turn_timeout_seconds(),+ )++ @property+ def root(self) -> Path:+ return self.db_path.parent++ def local_profiles(self) -> tuple[str, ...]:+ profiles = {"default"}+ profiles_dir = self.root / "profiles"+ if profiles_dir.is_dir():+ profiles.update(+ path.name for path in profiles_dir.iterdir() if path.is_dir()+ )+ return tuple(sorted(profiles))++ def bindings(self) -> tuple[HostedRoomBinding, ...]:+ local_gateway_id = hosted_rooms.local_authority_gateway_id()+ return tuple(+ HostedRoomBinding(+ room_id=str(room["room_id"]),+ gateway_id=str(room["authority_gateway_id"]),+ authority_epoch=int(room["authority_epoch"]),+ )+ for room in hosted_rooms.list_rooms(self.db_path)+ if str(room["authority_gateway_id"]) == local_gateway_id+ )++ def _owned_room(self, room_id: str) -> dict[str, Any]:+ room = hosted_rooms.room_state(self.db_path, room_id=room_id)+ if str(room["authority_gateway_id"]) != (+ hosted_rooms.local_authority_gateway_id()+ ):+ raise hosted_rooms.AuthorityConflictError(+ "This Group Chat is managed by another gateway."+ )+ return room++ @contextlib.contextmanager+ def _turn_lock(self, profile: str) -> Iterator[None]:+ from tools.bot_relay import acquire_turn_lock++ with acquire_turn_lock(self.root, profile):+ yield++ def start(self) -> None:+ self.runtime.start()++ def stop(self, *, timeout: float = 5.0) -> bool:+ return self.runtime.stop(timeout=timeout)++ def wakeup(self) -> None:+ self.runtime.wakeup()++ def _set_pending_action(+ self,+ room_id: str,+ member_id: str,+ action: Mapping[str, Any] | None,+ ) -> None:+ key = (room_id, member_id)+ with self._policy_lock:+ if action is None:+ self._pending_actions.pop(key, None)+ else:+ self._pending_actions[key] = {**action, "member_id": member_id}++ def _events(self, room_id: str) -> list[dict[str, Any]]:+ events: list[dict[str, Any]] = []+ cursor = 0+ while True:+ page = hosted_rooms.read_events(+ self.db_path,+ room_id=room_id,+ since_seq=cursor,+ limit=hosted_rooms.MAX_LOG_LIMIT,+ )+ rows = page.get("events")+ if isinstance(rows, list):+ events.extend(row for row in rows if isinstance(row, dict))+ next_cursor = int(page.get("cursor") or cursor)+ if not page.get("has_more"):+ return events+ if next_cursor <= cursor:+ raise RuntimeError("hosted room replay cursor did not advance")+ cursor = next_cursor++ def _append_plan(self, room_id: str, plan: discussion.PublicationPlan) -> None:+ for event in plan.events:+ hosted_rooms.append_event(+ self.db_path,+ **event.append_kwargs(room_id),+ )++ def _policy_snapshot(self, room: Mapping[str, Any]) -> PolicySnapshot:+ return self.policy_checkpoint.snapshot(+ room_id=str(room["room_id"]),+ latest_seq=int(room["latest_seq"]),+ )++ def _publish_terminal_tasks(+ self,+ room: Mapping[str, Any],+ ) -> bool:+ changed = False+ local_profiles = self.local_profiles()+ for status in ("deferred", "settled", "failed", "cancelled"):+ for task in driver.list_tasks(+ self.db_path,+ room_id=str(room["room_id"]),+ status=status,+ ):+ identity = task["identity"]+ if self.policy_checkpoint.publication_exists(+ room_id=str(room["room_id"]),+ task_id=identity.task_id,+ status=status,+ execution_generation=int(task["execution_generation"]),+ ):+ continue+ task_events = self.policy_checkpoint.events_for_task(+ room_id=str(room["room_id"]),+ source_event_seq=int(task["payload"]["source_event_seq"]),+ )+ plan = discussion.reconstruct_task_plan(+ room,+ task_events,+ task,+ local_profiles=local_profiles,+ )+ publication = discussion.plan_publication(+ room,+ task_events,+ plan,+ status=status,+ result=task.get("result"),+ execution_generation=(+ int(task["execution_generation"])+ if status == "deferred"+ else None+ ),+ local_profiles=local_profiles,+ )+ self._append_plan(str(room["room_id"]), publication)+ changed = True+ return changed++ def _append_room_status(+ self,+ room: Mapping[str, Any],+ decision: discussion.DiscussionDecision,+ ) -> None:+ if decision.discussion_event_id is None:+ return+ hosted_rooms.append_event(+ self.db_path,+ room_id=str(room["room_id"]),+ event_id=f"dactivity:{decision.discussion_event_id}:{decision.reason}",+ kind="room.activity",+ actor={"kind": "gateway", "id": str(room["authority_gateway_id"])},+ payload={+ "status": decision.status,+ "reason_code": decision.reason,+ "thread_id": decision.thread_id,+ "discussion_event_id": decision.discussion_event_id,+ },+ authority_gateway_id=str(room["authority_gateway_id"]),+ authority_epoch=int(room["authority_epoch"]),+ )++ def prepare_room(self, binding: HostedRoomBinding) -> None:+ with self._policy_lock:+ room = hosted_rooms.room_state(self.db_path, room_id=binding.room_id)+ snapshot = self._policy_snapshot(room)+ events = list(snapshot.events)+ if self._publish_terminal_tasks(room):+ room = hosted_rooms.room_state(+ self.db_path,+ room_id=binding.room_id,+ )+ snapshot = self._policy_snapshot(room)+ events = list(snapshot.events)+ self.policy_checkpoint.compact_completed(room_id=binding.room_id)+ driver.prune_published_terminal_tasks(+ self.db_path,+ room_id=binding.room_id,+ clock=self.runtime.clock,+ )+ if any(+ driver.list_tasks(+ self.db_path,+ room_id=binding.room_id,+ status=status,+ )+ for status in ("queued", "running", "stopping")+ ):+ return+ decision = discussion.plan_next_task(+ room,+ events,+ local_profiles=self.local_profiles(),+ initial_watermarks=snapshot.watermarks,+ )+ if decision.status == "task" and decision.task is not None:+ driver.admit_task(+ self.db_path,+ decision.task.identity,+ payload=decision.task.payload,+ clock=time.time,+ )+ # A stop can race the policy read from another process. Re-read+ # after admission and cancel before the runtime can execute a+ # task whose source event is now behind the room stop fence.+ fresh_room = hosted_rooms.room_state(+ self.db_path,+ room_id=binding.room_id,+ )+ stopped_through_seq = self._policy_snapshot(+ fresh_room+ ).stopped_through_seq+ if (+ decision.source_event_seq is not None+ and decision.source_event_seq < stopped_through_seq+ ):+ self.runtime.cancel(+ decision.task.identity,+ cancel_id=f"stop-fence:{stopped_through_seq}",+ )+ elif decision.status in {"settled", "bounded"}:+ self._append_room_status(room, decision)++ def publish_terminal(+ self,+ binding: HostedRoomBinding,+ _task: Mapping[str, Any],+ ) -> None:+ self.prepare_room(binding)+ self.runtime.wakeup()++ def create_room(self, *, room_id: str, name: str, members: Any) -> dict[str, Any]:+ normalized = discussion.validate_roster(+ members,+ local_profiles=self.local_profiles(),+ )+ room = hosted_rooms.create_room(+ self.db_path,+ room_id=room_id,+ name=name,+ members=[+ {+ "member_id": member.member_id,+ "profile": member.profile,+ "handle": member.handle,+ **(+ {"display_name": member.display_name}+ if member.display_name+ else {}+ ),+ }+ for member in normalized+ ],+ authority_gateway_id=hosted_rooms.local_authority_gateway_id(),+ )+ self.runtime.wakeup()+ return room++ def send(+ self,+ *,+ room_id: str,+ event_id: str,+ payload: Any,+ ) -> dict[str, Any]:+ normalized = discussion.validate_user_payload(payload)+ room = self._owned_room(room_id)+ event = hosted_rooms.append_event(+ self.db_path,+ room_id=room_id,+ event_id=event_id,+ kind="message.user",+ actor={"kind": "user", "id": "desktop"},+ payload=normalized,+ authority_gateway_id=str(room["authority_gateway_id"]),+ authority_epoch=int(room["authority_epoch"]),+ )+ binding = next(+ (+ candidate+ for candidate in self.bindings()+ if candidate.room_id == room_id+ ),+ None,+ )+ if binding is None:+ raise hosted_rooms.RoomNotFoundError("hosted room not found")+ self.prepare_room(binding)+ self.runtime.wakeup()+ return event++ def stop_room(+ self,+ room_id: str,+ *,+ cancel_id: str,+ require_acknowledged: bool = False,+ ) -> int:+ room = self._owned_room(room_id)+ hosted_rooms.request_room_stop(+ self.db_path,+ room_id=room_id,+ cancel_id=cancel_id,+ expected_gateway_id=str(room["authority_gateway_id"]),+ expected_epoch=int(room["authority_epoch"]),+ )+ cancelled = 0+ pending = 0+ with self._policy_lock:+ tasks = {}+ for status in (+ "queued",+ "running",+ "indeterminate",+ "deferred",+ "stopping",+ ):+ for task in driver.list_tasks(+ self.db_path,+ room_id=room_id,+ status=status,+ ):+ identity = task["identity"]+ tasks[(identity.room_id, identity.task_id)] = task+ for task in tasks.values():+ task_cancel_id = (+ str(task.get("cancel_id") or "")+ if task.get("status") == "stopping"+ else ""+ )+ result = self.runtime.cancel(+ task["identity"],+ cancel_id=task_cancel_id or cancel_id,+ )+ cancelled += 1+ if result["status"] == "stopping":+ pending += 1+ if require_acknowledged and pending:+ raise RuntimeError(+ "room work is still stopping; retry deletion after Stop completes"+ )+ self.runtime.wakeup()+ return cancelled++ def retry_room_task(self, room_id: str, *, task_id: str) -> dict[str, Any]:+ """Retry one uncertain or deferred task only after explicit user action."""++ task = next(+ (+ candidate+ for status in ("indeterminate", "deferred")+ for candidate in driver.list_tasks(+ self.db_path, room_id=room_id, status=status+ )+ if candidate["identity"].task_id == task_id+ ),+ None,+ )+ if task is None:+ raise driver.InvalidTaskTransitionError(+ "no retryable room task matches task_id"+ )+ return self.runtime.retry_indeterminate(task["identity"])++ def approve_room_task(+ self,+ room_id: str,+ *,+ member_id: str,+ task_id: str,+ execution_generation: int,+ choice: str,+ request_id: str | None = None,+ ) -> Mapping[str, Any]:+ """Resolve one exact local approval and wake room observation."""++ key = (room_id, member_id)+ with self._policy_lock:+ action = self._pending_actions.get(key)+ requested_approval_id = str(request_id or "")+ pending_approval_id = str((action or {}).get("request_id") or "")+ if (+ action is None+ or action.get("task_id") != task_id+ or int(action.get("execution_generation") or 0) != execution_generation+ or not requested_approval_id+ or requested_approval_id != pending_approval_id+ ):+ raise RuntimeError("room approval is no longer pending")+ if choice not in {"once", "deny"}:+ raise RuntimeError("room approval choice must be once or deny")+ session_id = str(action.get("session_id") or "")+ if not session_id:+ raise RuntimeError("local room approval identity is unavailable")+ result = self.rpc.approve(+ session_id=session_id,+ request_id=requested_approval_id,+ choice=choice,+ )+ if result is None:+ raise RuntimeError("room approval target is unavailable")+ with self._policy_lock:+ current = self._pending_actions.get(key)+ if (+ current is not None+ and str(current.get("request_id") or "") == requested_approval_id+ and current.get("task_id") == task_id+ and int(current.get("execution_generation") or 0)+ == execution_generation+ ):+ self._pending_actions.pop(key, None)+ self.runtime.wakeup()+ return result++ def status(self, room_id: str | None = None) -> dict[str, Any]:+ runtime = self.runtime.status()+ if room_id is None:+ return runtime+ tasks = driver.list_tasks(self.db_path, room_id=room_id)+ counts = Counter(str(task["status"]) for task in tasks)+ pending_actions = [+ {+ "kind": "retry",+ "task_id": task["identity"].task_id,+ }+ for task in tasks+ if task["status"] in {"indeterminate", "deferred"}+ ]+ with self._policy_lock:+ pending_actions.extend(+ dict(action)+ for (+ action_room_id,+ _member_id,+ ), action in self._pending_actions.items()+ if action_room_id == room_id+ )+ return {+ "running": runtime["running"],+ "working": bool(+ counts.get("running") or counts.get("queued") or counts.get("stopping")+ ),+ "blocked": room_id in runtime["blocked_rooms"]+ or bool(counts.get("indeterminate") or counts.get("stopping")),+ "counts": dict(counts),+ "pending_actions": pending_actions,+ }diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.pyindex cc5552a43c6..1c5781b687d 100644--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@ -214,5 +214,12 @@ def register(server) -> None:_registry.install(server)from . import methods_groups+ server._LONG_HANDLERS = server._LONG_HANDLERS | methods_groups.LONG_HANDLERS+ server.get_hosted_room_service = methods_groups.get_hosted_room_service+ server._WORKER_UNAVAILABLE = methods_groups._WORKER_UNAVAILABLE+ methods_groups.bind_server(server)+ methods_groups.register(server)+ from . import methods_groups+methods_groups.register(server)server._LONG_HANDLERS = server._LONG_HANDLERS | methods_groups.LONG_HANDLERSdiff --git a/tui_gateway/methods_groups.py b/tui_gateway/methods_groups.pyindex 9c014d797c4..c0ce55f24c1 100644--- a/tui_gateway/methods_groups.py+++ b/tui_gateway/methods_groups.py@@ -1,13 +1,15 @@"""Hosted-room JSON-RPC contract.-These methods expose durable room identity and an append-only, monotonic room-log. They deliberately do not drive Bot turns yet. ``groups.capabilities``-makes that boundary machine-readable so a hosted-aware Desktop cannot mistake-the log prototype for a complete gateway-side orchestrator.+These methods expose durable room identity, replay, and the process-owned+same-gateway Discussion driver. ``groups.capabilities`` keeps that boundary+machine-readable so older clients stay on the renderer-owned room path."""from .method_ctx import HandlerRegistry+import os+import threading+_registry = HandlerRegistry()method = _registry.method@@ -23,8 +25,74 @@ LONG_HANDLERS = frozenset({"groups.replica_state","groups.promote","groups.demote",+ "groups.stop",+ "groups.retry",+ "groups.approve",})+_service_lock = threading.Lock()+_bound_server = None+_service = None+++def bind_server(server) -> None:+ """Bind the fully initialized server module without starting a worker."""++ global _bound_server+ _bound_server = server+++def start_hosted_room_service():+ """Start one process-owned hosted room service idempotently."""++ global _service+ if _bound_server is None:+ return None+ from gateway.hosted_rooms import default_db_path+ from tui_gateway.hosted_room_service import HostedRoomService++ db_path = default_db_path()+ with _service_lock:+ if _service is not None and _service.db_path != db_path:+ _service.stop(timeout=1.0)+ _service = None+ if _service is None:+ _service = HostedRoomService(_bound_server, db_path=db_path)+ _service.start()+ return _service+++def stop_hosted_room_service(*, timeout: float = 5.0) -> bool:+ """Stop the process-owned worker without interrupting accepted turns."""++ global _service+ with _service_lock:+ service = _service+ if service is None:+ return True+ stopped = service.stop(timeout=timeout)+ if stopped and _service is service:+ _service = None+ return stopped+++def get_hosted_room_service():+ """Return the active service, if its lifecycle owner started it."""++ service = _service+ if service is None:+ return None+ try:+ status = service.runtime.status()+ except Exception:+ return None+ return service if status.get("running") and not status.get("stopping") else None+++_WORKER_UNAVAILABLE = (+ "Group Chat worker is unavailable. Restart the Hermes gateway and try again."+)+@method("groups.capabilities")def _(rid, params: dict) -> dict:@@ -35,11 +103,14 @@ def _(rid, params: dict) -> dict:local_authority_gateway_id,)+ service = get_hosted_room_service()+ driver_ready = bool(service and service.runtime.status()["running"])return _ok(rid,{"protocol_version": PROTOCOL_VERSION,- "driver": False,+ "driver": driver_ready,+ "persistent_process": os.getenv("HERMES_DESKTOP") != "1","authority_gateway_id": local_authority_gateway_id(),"features": ["authority_epoch",@@ -65,6 +136,9 @@ def _(rid, params: dict) -> dict:"groups.replica_state","groups.promote","groups.demote",+ "groups.stop",+ "groups.retry",+ "groups.approve",],"max_log_limit": MAX_LOG_LIMIT,},@@ -108,20 +182,16 @@ def _(rid, params: dict) -> dict:Required params: ``room_id``, ``name``, and ``members``. Authority isderived from this gateway's stable install identity, never from the client."""- from gateway.hosted_rooms import (- HostedRoomError,- create_room,- default_db_path,- local_authority_gateway_id,- )+ from gateway.hosted_rooms import HostedRoomErrortry:- room = create_room(- default_db_path(),+ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4123, _WORKER_UNAVAILABLE)+ room = service.create_room(room_id=params.get("room_id"),name=params.get("name"),members=params.get("members"),- authority_gateway_id=local_authority_gateway_id(),)return _ok(rid, {"room": room})except HostedRoomError as exc:@@ -137,14 +207,21 @@ def _(rid, params: dict) -> dict:from gateway.hosted_rooms import HostedRoomError, default_db_path, room_statetry:+ room = room_state(+ default_db_path(),+ room_id=params.get("room_id"),+ include_disbanded=params.get("include_disbanded") is True,+ )+ service = get_hosted_room_service()return _ok(rid,{- "room": room_state(- default_db_path(),- room_id=params.get("room_id"),- include_disbanded=params.get("include_disbanded") is True,- )+ "room": room,+ **(+ {"driver_status": service.status(str(room["room_id"]))}+ if service is not None and room.get("disbanded_at") is None+ else {}+ ),},)except HostedRoomError as exc:@@ -163,33 +240,17 @@ def _(rid, params: dict) -> dict:method. The actor is server-owned rather than trusted from params.Admission is durable; no Bot turn is started by this slice."""- from gateway.hosted_rooms import (- AuthorityConflictError,- HostedRoomError,- append_event,- default_db_path,- local_authority_gateway_id,- room_state,- user_event_id,- )+ from gateway.hosted_rooms import HostedRoomError, user_event_idtry:- room = room_state(default_db_path(), room_id=params.get("room_id"))- local_gateway_id = local_authority_gateway_id()- if str(room["authority_gateway_id"]) != local_gateway_id:- raise AuthorityConflictError(- "This Group Chat is managed by another gateway."- )client_event_id = params.get("event_id")- event = append_event(- default_db_path(),+ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4123, _WORKER_UNAVAILABLE)+ event = service.send(room_id=params.get("room_id"),event_id=user_event_id(client_event_id),- kind="message.user",- actor={"kind": "user", "id": "desktop"},payload=params.get("payload"),- authority_gateway_id=local_gateway_id,- authority_epoch=int(room["authority_epoch"]),)return _ok(rid,@@ -197,7 +258,7 @@ def _(rid, params: dict) -> dict:"event": event,"client_event_id": client_event_id,"accepted": True,- "driver_started": False,+ "driver_started": True,},)except HostedRoomError as exc:@@ -214,35 +275,53 @@ def _(rid, params: dict) -> dict:AuthorityConflictError,HostedRoomError,RoomHistoryExpiredError,- default_db_path,disband_room,local_authority_gateway_id,room_state,)try:- local_gateway_id = local_authority_gateway_id()+ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4123, _WORKER_UNAVAILABLE)++ def disband_with_state(state: dict | None = None) -> dict:+ local_gateway_id = local_authority_gateway_id()+ if state is not None and (+ str(state["authority_gateway_id"]) != local_gateway_id+ ):+ raise AuthorityConflictError(+ "This Group Chat is managed by another gateway."+ )+ return disband_room(+ service.db_path,+ room_id=params.get("room_id"),+ expected_gateway_id=str(+ local_gateway_id+ ),+ expected_epoch=int(+ state["authority_epoch"] if state is not None else 1+ ),+ )+try:- room = room_state(- default_db_path(),+ existing = room_state(+ service.db_path,room_id=params.get("room_id"),include_disbanded=True,)except RoomHistoryExpiredError:- room = {- "authority_gateway_id": local_gateway_id,- "authority_epoch": 1,- }- if str(room["authority_gateway_id"]) != local_gateway_id:- raise AuthorityConflictError(- "This Group Chat is managed by another gateway."- )- tombstone = disband_room(- default_db_path(),- room_id=params.get("room_id"),- expected_gateway_id=local_gateway_id,- expected_epoch=int(room["authority_epoch"]),+ tombstone = disband_with_state()+ return _ok(rid, {"tombstone": tombstone})+ if existing.get("disbanded_at") is not None:+ tombstone = disband_with_state(existing)+ return _ok(rid, {"tombstone": tombstone})+ service.stop_room(+ str(params.get("room_id") or ""),+ cancel_id=str(params.get("cancel_id") or "room-disbanded"),+ require_acknowledged=True,)+ tombstone = disband_with_state(existing)return _ok(rid, {"tombstone": tombstone})except HostedRoomError as exc:reason = getattr(exc, "reason", None)@@ -251,6 +330,75 @@ def _(rid, params: dict) -> dict:return _err(rid, 5114, str(exc))+@method("groups.stop")+def _(rid, params: dict) -> dict:+ """Durably cancel queued or running work for one hosted room."""++ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4115, "hosted room driver is unavailable")+ try:+ count = service.stop_room(+ str(params.get("room_id") or ""),+ cancel_id=str(params.get("cancel_id") or "desktop-stop"),+ )+ return _ok(rid, {"cancelled": count})+ except Exception as exc:+ return _err(rid, 5116, str(exc))+++@method("groups.approve")+def _(rid, params: dict) -> dict:+ """Resolve one exact approval requested by a local room member."""++ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4115, "hosted room driver is unavailable")+ try:+ result = service.approve_room_task(+ str(params.get("room_id") or ""),+ member_id=str(params.get("member_id") or ""),+ task_id=str(params.get("task_id") or ""),+ execution_generation=int(params.get("execution_generation") or 0),+ choice=str(params.get("choice") or ""),+ request_id=str(params.get("request_id") or ""),+ )+ return _ok(rid, {"approved": True, "result": result})+ except Exception as exc:+ return _err(rid, 5119, str(exc))+++@method("groups.retry")+def _(rid, params: dict) -> dict:+ """Retry one indeterminate room task after explicit user confirmation."""++ service = get_hosted_room_service()+ if service is None:+ return _err(rid, 4115, "hosted room driver is unavailable")+ try:+ task = service.retry_room_task(+ str(params.get("room_id") or ""),+ task_id=str(params.get("task_id") or ""),+ )+ identity = task.get("identity") if isinstance(task, dict) else None+ receipt = {+ "room_id": str(getattr(identity, "room_id", "") or ""),+ "task_id": str(getattr(identity, "task_id", "") or ""),+ "thread_id": str(getattr(identity, "thread_id", "") or ""),+ "turn_id": str(getattr(identity, "turn_id", "") or ""),+ "status": str(task.get("status") or "") if isinstance(task, dict) else "",+ "execution_generation": int(task.get("execution_generation") or 0)+ if isinstance(task, dict)+ else 0,+ "cancel_generation": int(task.get("cancel_generation") or 0)+ if isinstance(task, dict)+ else 0,+ }+ return _ok(rid, {"retried": True, "task": receipt})+ except Exception as exc:+ return _err(rid, 5118, str(exc))++@method("groups.log")def _(rid, params: dict) -> dict:"""Return a monotonic room-log delta after ``since_seq``."""diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 34e38aacf9a..66d2153b265 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -335,6 +335,67 @@ def _(rid, params: dict) -> dict:session, err = _sess_nowait(params, rid)if err:return err+ hosted_task = params.get("_hosted_task")+ hosted_terminal_callback = params.get("_hosted_terminal_callback")+ internal_hosted_submit = hosted_task is not None or hosted_terminal_callback is not None+ if internal_hosted_submit:+ if session.get("source") != "bot_room":+ return _err(rid, 4120, "hosted room turns require a bot_room session")+ if not isinstance(hosted_task, dict) or not callable(hosted_terminal_callback):+ return _err(rid, 4120, "invalid hosted room turn proof")+ required_hosted_fields = {+ "room_id",+ "task_id",+ "thread_id",+ "turn_id",+ "execution_generation",+ }+ if set(hosted_task) != required_hosted_fields or not all(+ isinstance(hosted_task.get(field), str) and hosted_task[field]+ for field in required_hosted_fields - {"execution_generation"}+ ) or not isinstance(hosted_task.get("execution_generation"), int):+ return _err(rid, 4120, "invalid hosted room turn proof")+ else:+ # Older Desktop builds know the `Group: <room-id>` session title but+ # not the hosted authority marker. Once a gateway owns that room, a+ # direct prompt into its member session would start a second renderer+ # driver. Fence it server-side instead of trusting client awareness.+ title = str(session.get("title") or "")+ if title.startswith("Group: "):+ room_id = title.removeprefix("Group: ").strip()+ if room_id:+ try:+ from gateway.hosted_rooms import (+ HostedRoomError,+ RoomProbeUnavailableError,+ default_db_path,+ probe_hosted_room,+ )++ hosted = probe_hosted_room(default_db_path(), room_id=room_id)+ except RoomProbeUnavailableError:+ return _err(+ rid,+ 5122,+ "Could not verify this group. Try again after the gateway recovers.",+ )+ except HostedRoomError:+ # Legacy Desktop sessions used the display name after+ # "Group: "; those names are not hosted room ids.+ pass+ except Exception:+ return _err(+ rid,+ 5122,+ "Could not verify this group. Try again after the gateway recovers.",+ )+ else:+ if hosted:+ return _err(+ rid,+ 4122,+ "This room is managed by its gateway. Update Hermes Desktop to continue it.",+ )if (limit_message := _ensure_active_session_slot(sid, session)) is not None:return _err(rid, 4090, limit_message)# Which desktop window this message was typed into. Rewritten on every@@ -357,6 +418,12 @@ def _(rid, params: dict) -> dict:)isolation_cfg = _load_dashboard_process_isolation_config()turn_isolation = _session_uses_compute_host(session, isolation_cfg)+ if internal_hosted_submit and turn_isolation:+ return _err(+ rid,+ 4121,+ "hosted room turns do not support isolated compute workers yet",+ )# Re-bind to the current client transport for this request. This keeps# streaming events on the active websocket even if an earlier disconnect# or fallback moved the session transport to stdio.@@ -366,6 +433,8 @@ def _(rid, params: dict) -> dict:busy_transport = Nonewith session["history_lock"]:if session.get("running"):+ if internal_hosted_submit:+ return _err(rid, 4091, "hosted room member session is busy")# Don't reject a mid-turn prompt — queue it (and, by default,# interrupt the live turn) so it runs as the next turn. The# provider interrupt itself must happen after this lock is@@ -812,6 +881,8 @@ def _(rid, params: dict) -> dict:session["running"] = Truesession["_turn_cancel_requested"] = Falsesession["last_active"] = time.time()+ if internal_hosted_submit:+ session["_hosted_room_task"] = dict(hosted_task)_start_inflight_turn(session, text)if turn_isolation:@@ -908,7 +979,14 @@ def _(rid, params: dict) -> dict:},)return- _run_prompt_submit(rid, sid, session, text, display_kind=display_kind)+ _run_prompt_submit(+ rid,+ sid,+ session,+ text,+ display_kind=display_kind,+ terminal_callback=hosted_terminal_callback,+ )run_thread = threading.Thread(target=run_after_agent_ready, daemon=True)# Keep a handle so session.interrupt can tell a live turn from a stuckdiff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 37844381f8f..c3a9d7c86c3 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -3361,6 +3361,18 @@ def _(rid, params: dict) -> dict:session, err = _sess_nowait(params, rid)if err:return err+ expected_hosted_task_id = str(+ params.get("expected_hosted_task_id") or ""+ ).strip()+ if expected_hosted_task_id:+ with session["history_lock"]:+ active_task = session.get("_hosted_room_task")+ if (+ not session.get("running")+ or not isinstance(active_task, dict)+ or active_task.get("task_id") != expected_hosted_task_id+ ):+ return _ok(rid, {"status": "not_interrupted", "interrupted": False})if _session_uses_compute_host(session):sid = str(params.get("session_id") or "")try:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 23a36b6248e..46be96ee92a 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -9801,6 +9801,12 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->same _run_prompt_submit machinery as every other synthesized turn — sothe client that just resumed streams it live."""+ # Hosted room turns are recovered by their durable task/lease state+ # machine. Generic session auto-continue would bypass its execution+ # generation and can duplicate work after a process restart.+ if session.get("source") == "bot_room":+ return None+home = _session_home(session)marker = read_turn_marker(home, session_key)if marker is None:@@ -10280,7 +10286,12 @@ def _inflight_snapshot(session: dict) -> dict | None:def _emit_terminal_turn_error(- sid: str, session: dict, error: Any, error_surface: Optional[dict] = None+ sid: str,+ session: dict,+ error: Any,+ error_surface: Optional[dict] = None,+ *,+ retire_marker: bool = True,) -> None:"""Close a failed turn with a terminal ``message.complete`` frame.@@ -10333,7 +10344,8 @@ def _emit_terminal_turn_error(rendered = ""if rendered:payload["rendered"] = rendered- _retire_turn_marker(session)+ if retire_marker:+ _retire_turn_marker(session)_emit("message.complete", sid, payload)@@ -12579,6 +12591,7 @@ def _run_prompt_submit(display_metadata: dict | None = None,image_paths: list[str] | None = None,queued_prompt_generation: int | None = None,+ terminal_callback: Callable[[dict[str, Any]], None] | None = None,) -> bool:with session["history_lock"]:if session.get("_closing"):@@ -12628,6 +12641,8 @@ def _run_prompt_submit(_emit("message.start", sid)def run():+ terminal_receipt_attempted = False+ terminal_receipt_committed = terminal_callback is None# The conversation runs on a fresh thread, so ContextVars from the RPC# dispatcher do not follow automatically. Rebind the exact transport# stored on this session generation before any tool can commission a@@ -13168,7 +13183,26 @@ def _run_prompt_submit(payload["recoverable"] = Trueif _error_surface:payload["error_surface"] = _error_surface- _retire_turn_marker(session, marker_key)+ if terminal_callback is not None:+ terminal_receipt_attempted = True+ terminal_callback(+ {+ "status": (+ "cancelled"+ if status == "interrupted"+ else "failed" if status == "error" else "settled"+ ),+ "text": raw if isinstance(raw, str) else str(raw),+ **(+ {"error": str(result.get("error") or raw)}+ if status == "error" and isinstance(result, dict)+ else {}+ ),+ }+ )+ terminal_receipt_committed = True+ if terminal_receipt_committed:+ _retire_turn_marker(session, marker_key)_emit("message.complete", sid, payload)# ── /goal continuation (Ralph-style loop) ─────────────────@@ -13348,11 +13382,25 @@ def _run_prompt_submit(# Keep the partial turn available to the next prompt; the durable# inflight record still carries the recoverable error state._restore_agent_history_after_turn_error(session, agent)+ if terminal_callback is not None and not terminal_receipt_attempted:+ terminal_receipt_attempted = True+ try:+ terminal_callback(+ {"status": "failed", "text": "", "error": str(e)}+ )+ terminal_receipt_committed = True+ except Exception:+ logger.exception("hosted room terminal receipt commit failed")try:# Close the turn with the same terminal error frame shape as# the returned-error path (uniform client handling), retaining# the failed turn for resume replay.- _emit_terminal_turn_error(sid, session, e)+ _emit_terminal_turn_error(+ sid,+ session,+ e,+ retire_marker=terminal_receipt_committed,+ )turn_error_retained = Trueexcept Exception as emit_exc:print(@@ -13447,7 +13495,10 @@ def _run_prompt_submit()# Backstop for turns that never reached a terminal frame (the# frame paths retire the marker as they emit).- _retire_turn_marker(session, marker_key)+ if terminal_receipt_committed:+ _retire_turn_marker(session, marker_key)+ with session["history_lock"]:+ session.pop("_hosted_room_task", None)session.pop("_auto_continue_scheduled", None)_emit_settled_session_info(sid, session, agent)