From 1ca96f8e32d9dfdc983a5ac9e388c314d72ee748 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:44:59 +0800 Subject: [PATCH 1/2] refactor(control_plane): modularize botmux_runtime under 750 LOC with zero Any Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/goal_channel_runtime.py | 7 +- .../goals/botmux_binding_store.py | 401 +++++ loopx/control_plane/goals/botmux_lifecycle.py | 302 ++++ loopx/control_plane/goals/botmux_runtime.py | 1529 ++--------------- loopx/control_plane/goals/botmux_status.py | 411 +++++ loopx/control_plane/goals/botmux_transport.py | 302 ++++ loopx/control_plane/goals/botmux_trigger.py | 316 ++++ .../test_botmux_runtime_contract.py | 141 ++ 8 files changed, 2014 insertions(+), 1395 deletions(-) create mode 100644 loopx/control_plane/goals/botmux_binding_store.py create mode 100644 loopx/control_plane/goals/botmux_lifecycle.py create mode 100644 loopx/control_plane/goals/botmux_status.py create mode 100644 loopx/control_plane/goals/botmux_transport.py create mode 100644 loopx/control_plane/goals/botmux_trigger.py create mode 100644 tests/control_plane/test_botmux_runtime_contract.py diff --git a/loopx/cli_commands/goal_channel_runtime.py b/loopx/cli_commands/goal_channel_runtime.py index 9cfb1efa84..ac520af713 100644 --- a/loopx/cli_commands/goal_channel_runtime.py +++ b/loopx/cli_commands/goal_channel_runtime.py @@ -3,9 +3,8 @@ from __future__ import annotations import argparse -from collections.abc import Callable +from collections.abc import Callable, Mapping from pathlib import Path -from typing import Any from ..control_plane.goals.botmux_runtime import ( BOTMUX_DEFAULT_ENDPOINT, @@ -20,7 +19,7 @@ def register_goal_channel_runtime_commands( - subparsers: argparse._SubParsersAction, + subparsers: argparse._SubParsersAction[argparse.ArgumentParser], add_subcommand_format: Callable[[argparse.ArgumentParser], None], ) -> None: runtime = subparsers.add_parser( @@ -95,7 +94,7 @@ def _add_runtime_common_args(parser: argparse.ArgumentParser) -> None: def run_goal_channel_runtime( args: argparse.Namespace, *, - registry: dict[str, Any], + registry: Mapping[str, object], registry_path: Path, ) -> dict[str, object]: goal_id = str(args.goal_id) diff --git a/loopx/control_plane/goals/botmux_binding_store.py b/loopx/control_plane/goals/botmux_binding_store.py new file mode 100644 index 0000000000..6a5121d1d2 --- /dev/null +++ b/loopx/control_plane/goals/botmux_binding_store.py @@ -0,0 +1,401 @@ +"""Typed local-private binding storage, receipt transitions, and public packet helpers.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Callable, Mapping +from datetime import datetime, timezone +from enum import Enum +from pathlib import Path +from typing import cast + +from ...file_lock import LockAcquireTimeoutError, lock_timeout_error_fields + +BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION = "loopx_goal_channel_botmux_binding_v0" +BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION = "loopx_goal_channel_runtime_operation_v0" +BOTMUX_PROVIDER = "botmux" +BOTMUX_DEFAULT_ENDPOINT = "http://127.0.0.1:7891" +BOTMUX_DEFAULT_TOKEN_ENV = "BOTMUX_DASHBOARD_TOKEN" +BOTMUX_HTTP_TIMEOUT_SECONDS = 4.0 + +_ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_PRIVATE_PACKET_KEYS = frozenset( + { + "bot_id", + "chat_id", + "endpoint", + "expected_working_dir", + "message_id", + "session_id", + "token", + "token_env", + "trigger_id", + } +) + +Payload = dict[str, object] +PayloadView = Mapping[str, object] +JsonRequester = Callable[..., Mapping[str, object]] +AtomicJsonWriter = Callable[[Path, PayloadView], None] +NowIsoFn = Callable[[], str] + + +class BotmuxApiError(RuntimeError): + """HTTP error raised when the botmux daemon rejects a request.""" + + def __init__(self, status: int, payload: PayloadView | None = None) -> None: + super().__init__(f"botmux API returned HTTP {status}") + self.status = status + self.payload: Payload = dict(payload or {}) + + +class BotmuxTransportError(RuntimeError): + """Transport or response-decoding failure talking to the botmux daemon.""" + + +class BotmuxDispatchState(str, Enum): + """Lifecycle states recorded in a local-private botmux dispatch receipt.""" + + ATTEMPTING = "attempting" + QUEUED = "queued" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + NOT_FOUND = "not_found" + UNKNOWN = "unknown" + REJECTED = "rejected" + + +_TERMINAL_DISPATCH_STATES = frozenset( + { + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + } +) + +_DISPATCH_TRANSITIONS: dict[ + BotmuxDispatchState | None, + frozenset[BotmuxDispatchState], +] = { + None: frozenset({BotmuxDispatchState.ATTEMPTING}), + BotmuxDispatchState.ATTEMPTING: frozenset( + { + BotmuxDispatchState.QUEUED, + BotmuxDispatchState.UNKNOWN, + BotmuxDispatchState.REJECTED, + } + ), + BotmuxDispatchState.QUEUED: frozenset( + { + BotmuxDispatchState.QUEUED, + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + BotmuxDispatchState.UNKNOWN, + } + ), + BotmuxDispatchState.RUNNING: frozenset( + { + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + BotmuxDispatchState.UNKNOWN, + } + ), + BotmuxDispatchState.UNKNOWN: frozenset( + { + BotmuxDispatchState.UNKNOWN, + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + } + ), + BotmuxDispatchState.COMPLETED: frozenset({BotmuxDispatchState.COMPLETED}), + BotmuxDispatchState.FAILED: frozenset({BotmuxDispatchState.FAILED}), + BotmuxDispatchState.NOT_FOUND: frozenset({BotmuxDispatchState.NOT_FOUND}), + BotmuxDispatchState.REJECTED: frozenset( + { + BotmuxDispatchState.REJECTED, + BotmuxDispatchState.ATTEMPTING, + } + ), +} + + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _as_mapping(value: object) -> PayloadView | None: + if isinstance(value, Mapping): + return cast(PayloadView, value) + return None + + +def _as_mutable_dict(value: object) -> Payload: + mapping = _as_mapping(value) + if mapping is None: + return {} + return {str(key): item for key, item in mapping.items()} + + +def _as_string_dict(value: object) -> Payload | None: + if not isinstance(value, dict): + return None + mapping = cast(Mapping[object, object], value) + normalized: Payload = {} + for key, item in mapping.items(): + if not isinstance(key, str): + return None + normalized[key] = item + return normalized + + +def default_botmux_runtime_binding_path(registry_path: Path) -> Path: + """Return the local-private binding path beside a project source registry.""" + expanded = registry_path.expanduser().resolve() + if expanded.parent.name != ".loopx": + raise ValueError( + "Botmux Goal Channel runtime binding requires a project source registry" + ) + return expanded.parent / "goal-channel-runtime.json" + + +def read_botmux_runtime_binding(path: Path) -> Payload: + """Read and validate the local-private botmux runtime binding file.""" + binding_path = path.expanduser() + if not binding_path.exists(): + return { + "schema_version": BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION, + "bindings": {}, + } + raw_payload = cast(object, json.loads(binding_path.read_text(encoding="utf-8"))) + payload = _as_string_dict(raw_payload) + if ( + payload is None + or payload.get("schema_version") != BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION + or not isinstance(payload.get("bindings"), dict) + ): + raise ValueError("Botmux Goal Channel runtime binding is invalid") + return payload + + +def botmux_binding_for_goal( + payload: PayloadView, + goal_id: str, +) -> Payload | None: + """Return a shallow copy of the binding dictionary for ``goal_id`` if present.""" + bindings = _as_mapping(payload.get("bindings")) + binding = _as_mapping(bindings.get(goal_id)) if bindings is not None else None + return dict(binding) if binding is not None else None + + +def _save_binding( + *, + binding_path: Path, + payload: PayloadView, + goal_id: str, + binding: PayloadView, + writer: AtomicJsonWriter, +) -> None: + bindings = _as_mapping(payload.get("bindings")) + mutable: dict[str, object] = dict(bindings) if bindings is not None else {} + mutable[goal_id] = dict(binding) + writer( + binding_path, + { + "schema_version": BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION, + "bindings": mutable, + }, + ) + + +def _dispatch_state(value: object) -> BotmuxDispatchState | None: + try: + return BotmuxDispatchState(str(value or "")) + except ValueError: + return None + + +def _transition_dispatch_receipt( + receipt: PayloadView | None, + *, + state: BotmuxDispatchState, + timestamp_field: str, + updates: PayloadView | None = None, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + current = ( + _dispatch_state(receipt.get("state")) if receipt is not None else None + ) + allowed = _DISPATCH_TRANSITIONS.get(current, frozenset()) + if state not in allowed: + raise ValueError( + f"invalid botmux dispatch transition: " + f"{current.value if current else 'none'}->{state.value}" + ) + transitioned: Payload = dict(receipt or {}) + transitioned["state"] = state.value + transitioned[timestamp_field] = now_iso() + if updates: + transitioned.update(dict(updates)) + return transitioned + + +def _persist_dispatch_receipt( + *, + binding_path: Path, + goal_id: str, + binding: Payload, + dispatch_key: str, + state: BotmuxDispatchState, + timestamp_field: str, + updates: PayloadView | None = None, + session: PayloadView | None = None, + writer: AtomicJsonWriter, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + payload = read_botmux_runtime_binding(binding_path) + current_binding = botmux_binding_for_goal(payload, goal_id) + if current_binding is None: + raise ValueError("botmux runtime binding disappeared during dispatch") + receipts = _as_mutable_dict(current_binding.get("receipts")) + receipt = _transition_dispatch_receipt( + _as_mapping(receipts.get(dispatch_key)), + state=state, + timestamp_field=timestamp_field, + updates=updates, + now_iso=now_iso, + ) + receipts[dispatch_key] = receipt + current_binding["receipts"] = receipts + if session is not None: + current_binding["session"] = dict(session) + binding.clear() + binding.update(current_binding) + _save_binding( + binding_path=binding_path, + payload=payload, + goal_id=goal_id, + binding=current_binding, + writer=writer, + ) + return receipt + + +def _active_dispatch_receipt( + binding: PayloadView, +) -> tuple[str, Payload] | None: + receipts = _as_mapping(binding.get("receipts")) or {} + session = _as_mapping(binding.get("session")) or {} + active_key = str(session.get("active_dispatch_key") or "").strip() + active = _as_mapping(receipts.get(active_key)) if active_key else None + if active_key and active is not None: + return active_key, dict(active) + + candidates: list[tuple[str, Payload]] = [] + for key, value in receipts.items(): + mapping = _as_mapping(value) + if mapping is None: + continue + if _dispatch_state(mapping.get("state")) in { + BotmuxDispatchState.ATTEMPTING, + BotmuxDispatchState.UNKNOWN, + BotmuxDispatchState.REJECTED, + }: + candidates.append((str(key), dict(mapping))) + if not candidates: + return None + return max( + candidates, + key=lambda item: str( + item[1].get("unknown_at") + or item[1].get("rejected_at") + or item[1].get("attempted_at") + or "" + ), + ) + + +def _assert_public_packet(packet: PayloadView) -> None: + def visit(value: object) -> None: + if isinstance(value, Mapping): + mapping = cast(Mapping[object, object], value) + for key, child in mapping.items(): + if key in _PRIVATE_PACKET_KEYS: + raise ValueError( + f"public botmux packet contains private key `{key}`" + ) + visit(child) + elif isinstance(value, list): + items = cast(list[object], value) + for child in items: + visit(child) + + visit(packet) + + +def _operation_packet( + *, + ok: bool, + goal_id: str, + operation: str, + execute: bool, + status: str, + public_summary: str, + blocker: str | None = None, + external_write_performed: bool = False, + readback_verified: bool = False, + idempotency_key: str | None = None, + receipt_id: str | None = None, + details: PayloadView | None = None, +) -> Payload: + packet: Payload = { + "schema_version": BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION, + "ok": ok, + "goal_id": goal_id, + "provider": BOTMUX_PROVIDER, + "operation": operation, + "execute": execute, + "status": status, + "external_write_performed": external_write_performed, + "readback_verified": readback_verified, + "idempotency_key": idempotency_key, + "receipt_id": receipt_id, + "public_summary": public_summary, + "private_provider_payload_captured": False, + } + if blocker: + packet["blocker"] = blocker + if details: + packet["details"] = dict(details) + _assert_public_packet(packet) + return packet + + +def _lock_timeout_packet( + *, + goal_id: str, + operation: str, + execute: bool, + error: LockAcquireTimeoutError, +) -> Payload: + packet = _operation_packet( + ok=False, + goal_id=goal_id, + operation=operation, + execute=execute, + status="blocked", + blocker="botmux_runtime_lock_timeout", + public_summary=( + "the botmux runtime binding is busy; inspect the lock holder and retry" + ), + ) + packet.update(lock_timeout_error_fields(error)) + _assert_public_packet(packet) + return packet diff --git a/loopx/control_plane/goals/botmux_lifecycle.py b/loopx/control_plane/goals/botmux_lifecycle.py new file mode 100644 index 0000000000..0b675f30c9 --- /dev/null +++ b/loopx/control_plane/goals/botmux_lifecycle.py @@ -0,0 +1,302 @@ +"""Goal lookup, binding setup/doctor/disable, and deterministic turn keys for botmux.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from pathlib import Path +from typing import cast + +from ...paths import registry_project_root +from ...registry import registry_goals +from .botmux_binding_store import ( + AtomicJsonWriter, + BOTMUX_DEFAULT_TOKEN_ENV, + BOTMUX_PROVIDER, + BotmuxApiError, + BotmuxTransportError, + JsonRequester, + NowIsoFn, + Payload, + PayloadView, + _as_mapping, + _now_iso, + _operation_packet, + _save_binding, + botmux_binding_for_goal, + read_botmux_runtime_binding, +) +from .botmux_transport import ( + _probe_botmux, + _validated_endpoint, + _validated_private_id, + _validated_token_env, +) + + +def _goal_from_registry( + registry: PayloadView, + goal_id: str, +) -> Payload: + raw_registry = {str(key): value for key, value in registry.items()} + for goal in registry_goals(raw_registry): + if str(goal.get("id") or "") == goal_id: + normalized: Payload = {} + for key, value in cast(Mapping[object, object], goal).items(): + normalized[str(key)] = value + return normalized + raise ValueError(f"Goal `{goal_id}` is not registered") + + +def _probe_error_packet( + *, + goal_id: str, + operation: str, + execute: bool, + error: Exception, + invalid_config_summary: str, +) -> Payload: + if isinstance(error, ValueError): + blocker = ( + "botmux_auth_unavailable" + if "token is unavailable" in str(error) + else "botmux_configuration_invalid" + ) + summary = invalid_config_summary + elif isinstance(error, BotmuxApiError): + blocker = "botmux_api_rejected" + summary = "botmux rejected the runtime readiness probe" + else: + blocker = "botmux_unreachable" + summary = "the configured botmux daemon is unreachable" + return _operation_packet( + ok=False, + goal_id=goal_id, + operation=operation, + execute=execute, + status="blocked", + blocker=blocker, + public_summary=summary, + ) + + +def _setup_botmux_runtime( + *, + registry: PayloadView, + registry_path: Path, + goal_id: str, + binding_path: Path, + endpoint: str, + bot_id: str, + chat_id: str, + token_env: str = BOTMUX_DEFAULT_TOKEN_ENV, + execute: bool = False, + requester: JsonRequester, + writer: AtomicJsonWriter, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + _goal_from_registry(registry, goal_id) + payload = read_botmux_runtime_binding(binding_path) + prior: Payload = botmux_binding_for_goal(payload, goal_id) or {} + endpoint = _validated_endpoint(endpoint) + bot_id = _validated_private_id(bot_id, "bot id") + chat_id = _validated_private_id(chat_id, "chat id") + token_env = _validated_token_env(token_env) + expected_working_dir = registry_project_root(registry_path) + same_route = bool( + prior.get("endpoint") == endpoint + and prior.get("bot_id") == bot_id + and prior.get("chat_id") == chat_id + and prior.get("token_env") == token_env + and prior.get("expected_working_dir") == str(expected_working_dir) + ) + prior_session = _as_mapping(prior.get("session")) + prior_receipts = _as_mapping(prior.get("receipts")) + binding: Payload = { + "goal_id": goal_id, + "provider": BOTMUX_PROVIDER, + "enabled": True, + "endpoint": endpoint, + "bot_id": bot_id, + "chat_id": chat_id, + "token_env": token_env, + "expected_working_dir": str(expected_working_dir), + "session": dict(prior_session) if same_route and prior_session else {}, + "receipts": dict(prior_receipts) if same_route and prior_receipts else {}, + } + try: + probe = _probe_botmux(binding=binding, requester=requester) + except (ValueError, BotmuxApiError, BotmuxTransportError) as exc: + return _probe_error_packet( + goal_id=goal_id, + operation="runtime_setup", + execute=execute, + error=exc, + invalid_config_summary="the botmux runtime binding could not be verified", + ) + if execute: + binding["verified_at"] = now_iso() + _save_binding( + binding_path=binding_path, + payload=payload, + goal_id=goal_id, + binding=binding, + writer=writer, + ) + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_setup", + execute=execute, + status="configured" if execute else "preview_ready", + public_summary=( + "configured the verified botmux runtime binding" + if execute + else "the botmux runtime binding is ready to configure" + ), + readback_verified=bool(execute), + details=probe, + ) + + +def _doctor_botmux_runtime( + *, + goal_id: str, + binding_path: Path, + requester: JsonRequester, +) -> Payload: + binding = botmux_binding_for_goal( + read_botmux_runtime_binding(binding_path), + goal_id, + ) + if binding is None or binding.get("enabled") is not True: + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_doctor", + execute=False, + status="blocked", + blocker="botmux_binding_missing", + public_summary="configure a botmux runtime binding for this goal", + ) + try: + probe = _probe_botmux(binding=binding, requester=requester) + except (ValueError, BotmuxApiError, BotmuxTransportError) as exc: + return _probe_error_packet( + goal_id=goal_id, + operation="runtime_doctor", + execute=False, + error=exc, + invalid_config_summary="the botmux runtime binding is not ready", + ) + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_doctor", + execute=False, + status="ready", + public_summary="the botmux runtime binding is ready", + readback_verified=True, + details=probe, + ) + + +def _disable_botmux_runtime( + *, + goal_id: str, + binding_path: Path, + execute: bool = False, + writer: AtomicJsonWriter, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + payload = read_botmux_runtime_binding(binding_path) + binding = botmux_binding_for_goal(payload, goal_id) + if binding is None: + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_disable", + execute=execute, + status="not_configured", + public_summary="no botmux runtime binding is configured for this goal", + ) + if execute: + binding["enabled"] = False + binding["session"] = {} + binding["disabled_at"] = now_iso() + _save_binding( + binding_path=binding_path, + payload=payload, + goal_id=goal_id, + binding=binding, + writer=writer, + ) + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_disable", + execute=execute, + status="disabled" if execute else "preview_ready", + public_summary=( + "disabled the botmux runtime binding for this goal" + if execute + else "the botmux runtime binding is ready to disable" + ), + readback_verified=bool(execute), + ) + + +def build_botmux_loopx_instruction(goal_id: str) -> str: + """Build the default LoopX continuation prompt dispatched to botmux.""" + return ( + f"Continue the active LoopX goal `{goal_id}` in the current project using " + "the installed LoopX CLI or managed skill. Read canonical goal state and " + "execute the active next action. Complete a coherent artifact, targeted " + "validation, and state writeback. Continue the next bounded segment while " + "no explicit gate, quota, authority, or production access blocker applies. " + "When stopping, report the exact stop reason and a pasteable resume command." + ) + + +def goal_runtime_revision( + *, + registry: PayloadView, + registry_path: Path, + goal_id: str, +) -> str: + """Derive a short digest representing the current persisted Goal state file.""" + goal = _goal_from_registry(registry, goal_id) + raw_state_path = str(goal.get("state_file") or "").strip() + state_bytes = b"" + if raw_state_path: + state_path = Path(raw_state_path).expanduser() + if not state_path.is_absolute(): + state_path = registry_project_root(registry_path) / state_path + try: + state_bytes = state_path.read_bytes() + except OSError: + state_bytes = b"" + digest = hashlib.sha256( + goal_id.encode("utf-8") + b"\0" + state_bytes + ).hexdigest() + return digest[:24] + + +def _dispatch_key(*, goal_id: str, revision: str, instruction: str) -> str: + digest = hashlib.sha256( + json.dumps( + [goal_id, revision, instruction], + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + return f"sha256:{digest}" + + +def _provider_turn_key(dispatch_key: str) -> str: + return f"loopx-{dispatch_key.removeprefix('sha256:')[:32]}" + + +def _receipt_id(dispatch_key: str) -> str: + return f"runtime_{dispatch_key.removeprefix('sha256:')[:16]}" diff --git a/loopx/control_plane/goals/botmux_runtime.py b/loopx/control_plane/goals/botmux_runtime.py index 93da09c522..ea060f0d37 100644 --- a/loopx/control_plane/goals/botmux_runtime.py +++ b/loopx/control_plane/goals/botmux_runtime.py @@ -1,159 +1,103 @@ +"""Public facade and lock-fenced entrypoints for the botmux Goal Channel runtime.""" + from __future__ import annotations -import hashlib -import ipaddress import json import os -import re import tempfile -from collections.abc import Callable, Mapping -from datetime import datetime, timezone -from enum import Enum from pathlib import Path -from typing import Any -from urllib.error import HTTPError, URLError -from urllib.parse import quote, urlparse -from urllib.request import HTTPRedirectHandler, Request, build_opener from ...file_lock import LockAcquireTimeoutError, exclusive_file_lock -from ...file_lock import lock_timeout_error_fields -from ...paths import registry_project_root -from ...public_safe_text import OPAQUE_ID_PATTERN as _SAFE_TOKEN -from ...registry import registry_goals - - -BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION = "loopx_goal_channel_botmux_binding_v0" -BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION = "loopx_goal_channel_runtime_operation_v0" -BOTMUX_PROVIDER = "botmux" -BOTMUX_DEFAULT_ENDPOINT = "http://127.0.0.1:7891" -BOTMUX_DEFAULT_TOKEN_ENV = "BOTMUX_DASHBOARD_TOKEN" -BOTMUX_HTTP_TIMEOUT_SECONDS = 4.0 - -_ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") -_PRIVATE_PACKET_KEYS = { - "bot_id", - "chat_id", - "endpoint", - "expected_working_dir", - "message_id", - "session_id", - "token", - "token_env", - "trigger_id", -} - -JsonRequester = Callable[..., dict[str, Any]] - - -class BotmuxApiError(RuntimeError): - def __init__(self, status: int, payload: Mapping[str, Any] | None = None) -> None: - super().__init__(f"botmux API returned HTTP {status}") - self.status = status - self.payload = dict(payload or {}) - - -class BotmuxTransportError(RuntimeError): - pass - - -class BotmuxDispatchState(str, Enum): - ATTEMPTING = "attempting" - QUEUED = "queued" - RUNNING = "running" - COMPLETED = "completed" - FAILED = "failed" - NOT_FOUND = "not_found" - UNKNOWN = "unknown" - REJECTED = "rejected" - - -_TERMINAL_DISPATCH_STATES = frozenset( - { - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - } +from ...public_safe_text import OPAQUE_ID_PATTERN +from .botmux_binding_store import ( + BOTMUX_DEFAULT_ENDPOINT as BOTMUX_DEFAULT_ENDPOINT, + BOTMUX_DEFAULT_TOKEN_ENV as BOTMUX_DEFAULT_TOKEN_ENV, + BOTMUX_HTTP_TIMEOUT_SECONDS as BOTMUX_HTTP_TIMEOUT_SECONDS, + BOTMUX_PROVIDER as BOTMUX_PROVIDER, + BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION as BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION, + BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION as BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION, + BotmuxApiError as BotmuxApiError, + BotmuxDispatchState as BotmuxDispatchState, + BotmuxTransportError as BotmuxTransportError, + JsonRequester as JsonRequester, + Payload as Payload, + PayloadView as PayloadView, + _DISPATCH_TRANSITIONS as _DISPATCH_TRANSITIONS, + _ENV_NAME as _ENV_NAME, + _PRIVATE_PACKET_KEYS as _PRIVATE_PACKET_KEYS, + _TERMINAL_DISPATCH_STATES as _TERMINAL_DISPATCH_STATES, + _active_dispatch_receipt as _active_dispatch_receipt, + _assert_public_packet as _assert_public_packet, + _dispatch_state as _dispatch_state, + _lock_timeout_packet as _lock_timeout_packet, + _now_iso as _store_now_iso, + _operation_packet as _operation_packet, + _persist_dispatch_receipt as _persist_dispatch_receipt, + _save_binding as _save_binding, + _transition_dispatch_receipt as _transition_dispatch_receipt, + botmux_binding_for_goal as botmux_binding_for_goal, + default_botmux_runtime_binding_path as default_botmux_runtime_binding_path, + read_botmux_runtime_binding as read_botmux_runtime_binding, ) +from .botmux_lifecycle import ( + _disable_botmux_runtime as _disable_botmux_runtime, + _dispatch_key as _dispatch_key, + _doctor_botmux_runtime, + _goal_from_registry as _goal_from_registry, + _provider_turn_key as _provider_turn_key, + _receipt_id as _receipt_id, + _setup_botmux_runtime as _setup_botmux_runtime, + build_botmux_loopx_instruction as build_botmux_loopx_instruction, + goal_runtime_revision as goal_runtime_revision, +) +from .botmux_transport import ( + _NO_REDIRECT_OPENER as _NO_REDIRECT_OPENER, + _NoRedirectHandler as _NoRedirectHandler, + _dashboard_auth_for_binding as _dashboard_auth_for_binding, + _normalized_working_dir as _normalized_working_dir, + _probe_botmux as _probe_botmux, + _request_json as _request_json, + _validated_endpoint as _validated_endpoint, + _validated_private_id as _validated_private_id, + _validated_token_env as _validated_token_env, +) +from .botmux_status import _status_botmux_runtime as _status_botmux_runtime +from .botmux_trigger import _trigger_botmux_runtime as _trigger_botmux_runtime + +__all__ = [ + "BOTMUX_DEFAULT_ENDPOINT", + "BOTMUX_DEFAULT_TOKEN_ENV", + "BOTMUX_HTTP_TIMEOUT_SECONDS", + "BOTMUX_PROVIDER", + "BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION", + "BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION", + "BotmuxApiError", + "BotmuxDispatchState", + "BotmuxTransportError", + "JsonRequester", + "Payload", + "PayloadView", + "botmux_binding_for_goal", + "build_botmux_loopx_instruction", + "default_botmux_runtime_binding_path", + "disable_botmux_runtime", + "doctor_botmux_runtime", + "goal_runtime_revision", + "read_botmux_runtime_binding", + "setup_botmux_runtime", + "status_botmux_runtime", + "trigger_botmux_runtime", +] + + +_SAFE_TOKEN = OPAQUE_ID_PATTERN -_DISPATCH_TRANSITIONS: dict[ - BotmuxDispatchState | None, - frozenset[BotmuxDispatchState], -] = { - None: frozenset({BotmuxDispatchState.ATTEMPTING}), - BotmuxDispatchState.ATTEMPTING: frozenset( - { - BotmuxDispatchState.QUEUED, - BotmuxDispatchState.UNKNOWN, - BotmuxDispatchState.REJECTED, - } - ), - BotmuxDispatchState.QUEUED: frozenset( - { - BotmuxDispatchState.QUEUED, - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - BotmuxDispatchState.UNKNOWN, - } - ), - BotmuxDispatchState.RUNNING: frozenset( - { - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - BotmuxDispatchState.UNKNOWN, - } - ), - BotmuxDispatchState.UNKNOWN: frozenset( - { - BotmuxDispatchState.UNKNOWN, - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - } - ), - BotmuxDispatchState.COMPLETED: frozenset({BotmuxDispatchState.COMPLETED}), - BotmuxDispatchState.FAILED: frozenset({BotmuxDispatchState.FAILED}), - BotmuxDispatchState.NOT_FOUND: frozenset({BotmuxDispatchState.NOT_FOUND}), - BotmuxDispatchState.REJECTED: frozenset( - { - BotmuxDispatchState.REJECTED, - BotmuxDispatchState.ATTEMPTING, - } - ), -} - - -class _NoRedirectHandler(HTTPRedirectHandler): - def redirect_request( - self, - req: Request, - fp: Any, - code: int, - msg: str, - headers: Any, - newurl: str, - ) -> None: - return None - - -_NO_REDIRECT_OPENER = build_opener(_NoRedirectHandler()) - - -def default_botmux_runtime_binding_path(registry_path: Path) -> Path: - expanded = registry_path.expanduser().resolve() - if expanded.parent.name != ".loopx": - raise ValueError( - "Botmux Goal Channel runtime binding requires a project source registry" - ) - return expanded.parent / "goal-channel-runtime.json" +def _now_iso() -> str: + return _store_now_iso() -def _write_private_json_atomic(path: Path, payload: Mapping[str, Any]) -> None: +def _write_private_json_atomic(path: Path, payload: PayloadView) -> None: destination = path.expanduser() destination.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary_name = tempfile.mkstemp( @@ -176,621 +120,32 @@ def _write_private_json_atomic(path: Path, payload: Mapping[str, Any]) -> None: temporary.unlink(missing_ok=True) -def read_botmux_runtime_binding(path: Path) -> dict[str, Any]: - binding_path = path.expanduser() - if not binding_path.exists(): - return { - "schema_version": BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION, - "bindings": {}, - } - payload = json.loads(binding_path.read_text(encoding="utf-8")) - if ( - not isinstance(payload, dict) - or payload.get("schema_version") != BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION - or not isinstance(payload.get("bindings"), dict) - ): - raise ValueError("Botmux Goal Channel runtime binding is invalid") - return payload - - -def botmux_binding_for_goal( - payload: Mapping[str, Any], - goal_id: str, -) -> dict[str, Any] | None: - bindings = payload.get("bindings") - binding = bindings.get(goal_id) if isinstance(bindings, Mapping) else None - return dict(binding) if isinstance(binding, Mapping) else None - - -def _save_binding( - *, - binding_path: Path, - payload: Mapping[str, Any], - goal_id: str, - binding: Mapping[str, Any], -) -> None: - bindings = payload.get("bindings") - mutable = dict(bindings) if isinstance(bindings, Mapping) else {} - mutable[goal_id] = dict(binding) - _write_private_json_atomic( - binding_path, - { - "schema_version": BOTMUX_RUNTIME_BINDING_SCHEMA_VERSION, - "bindings": mutable, - }, - ) - - -def _dispatch_state(value: object) -> BotmuxDispatchState | None: - try: - return BotmuxDispatchState(str(value or "")) - except ValueError: - return None - - -def _transition_dispatch_receipt( - receipt: Mapping[str, Any] | None, - *, - state: BotmuxDispatchState, - timestamp_field: str, - updates: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - current = _dispatch_state(receipt.get("state")) if isinstance(receipt, Mapping) else None - allowed = _DISPATCH_TRANSITIONS.get(current, frozenset()) - if state not in allowed: - raise ValueError( - f"invalid botmux dispatch transition: " - f"{current.value if current else 'none'}->{state.value}" - ) - transitioned = dict(receipt or {}) - transitioned["state"] = state.value - transitioned[timestamp_field] = _now_iso() - if updates: - transitioned.update(dict(updates)) - return transitioned - - -def _persist_dispatch_receipt( - *, - binding_path: Path, - goal_id: str, - binding: dict[str, Any], - dispatch_key: str, - state: BotmuxDispatchState, - timestamp_field: str, - updates: Mapping[str, Any] | None = None, - session: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - payload = read_botmux_runtime_binding(binding_path) - current_binding = botmux_binding_for_goal(payload, goal_id) - if current_binding is None: - raise ValueError("botmux runtime binding disappeared during dispatch") - receipts = dict(current_binding.get("receipts") or {}) - receipt = _transition_dispatch_receipt( - receipts.get(dispatch_key) - if isinstance(receipts.get(dispatch_key), Mapping) - else None, - state=state, - timestamp_field=timestamp_field, - updates=updates, - ) - receipts[dispatch_key] = receipt - current_binding["receipts"] = receipts - if session is not None: - current_binding["session"] = dict(session) - binding.clear() - binding.update(current_binding) - _save_binding( - binding_path=binding_path, - payload=payload, - goal_id=goal_id, - binding=current_binding, - ) - return receipt - - -def _active_dispatch_receipt( - binding: Mapping[str, Any], -) -> tuple[str, dict[str, Any]] | None: - receipts = binding.get("receipts") - receipts = receipts if isinstance(receipts, Mapping) else {} - session = binding.get("session") - session = session if isinstance(session, Mapping) else {} - active_key = str(session.get("active_dispatch_key") or "").strip() - active = receipts.get(active_key) if active_key else None - if active_key and isinstance(active, Mapping): - return active_key, dict(active) - - candidates = [ - (str(key), dict(value)) - for key, value in receipts.items() - if isinstance(value, Mapping) - and _dispatch_state(value.get("state")) - in { - BotmuxDispatchState.ATTEMPTING, - BotmuxDispatchState.UNKNOWN, - BotmuxDispatchState.REJECTED, - } - ] - if not candidates: - return None - return max( - candidates, - key=lambda item: str( - item[1].get("unknown_at") - or item[1].get("rejected_at") - or item[1].get("attempted_at") - or "" - ), - ) - - -def _goal_from_registry( - registry: Mapping[str, Any], - goal_id: str, -) -> dict[str, Any]: - match = next( - ( - dict(goal) - for goal in registry_goals(dict(registry)) - if str(goal.get("id") or "") == goal_id - ), - None, - ) - if match is None: - raise ValueError(f"Goal `{goal_id}` is not registered") - return match - - -def _validated_endpoint(value: str) -> str: - endpoint = str(value or "").strip().rstrip("/") - parsed = urlparse(endpoint) - if ( - parsed.scheme not in {"http", "https"} - or not parsed.hostname - or parsed.username - or parsed.password - or parsed.query - or parsed.fragment - or parsed.path not in {"", "/"} - ): - raise ValueError("botmux endpoint must be one HTTP(S) origin") - if parsed.scheme == "http": - hostname = str(parsed.hostname or "").lower() - try: - is_loopback = ipaddress.ip_address(hostname).is_loopback - except ValueError: - is_loopback = hostname == "localhost" - if not is_loopback: - raise ValueError("remote botmux endpoint must use HTTPS") - return endpoint - - -def _validated_token_env(value: str) -> str: - token_env = str(value or "").strip() - if not _ENV_NAME.fullmatch(token_env): - raise ValueError("botmux token env must be one environment variable name") - return token_env - - -def _validated_private_id(value: str, label: str) -> str: - normalized = str(value or "").strip() - if not _SAFE_TOKEN.fullmatch(normalized): - raise ValueError(f"botmux {label} is invalid") - return normalized +def _atomic_write(path: Path, payload: PayloadView) -> None: + _write_private_json_atomic(path, payload) -def _normalized_working_dir(value: str) -> Path: - working_dir = Path(str(value or "").strip()).expanduser() - if not str(value or "").strip() or not working_dir.is_absolute(): - raise ValueError("botmux working directory must be absolute") - return working_dir.resolve() +def _current_iso() -> str: + return _now_iso() -def _dashboard_auth_for_binding(binding: Mapping[str, Any]) -> str: - token_env = _validated_token_env(str(binding.get("token_env") or "")) - token = str(os.environ.get(token_env) or "").strip() - if not token or any(ord(character) <= 32 for character in token) or ";" in token: - raise ValueError("botmux dashboard token is unavailable") - return token - - -def _request_json( - *, - endpoint: str, - path: str, - method: str = "GET", - dashboard_auth: str | None = None, - payload: Mapping[str, Any] | None = None, - timeout_seconds: float = BOTMUX_HTTP_TIMEOUT_SECONDS, -) -> dict[str, Any]: - body = ( - json.dumps(dict(payload), ensure_ascii=False, separators=(",", ":")).encode( - "utf-8" - ) - if payload is not None - else None - ) - headers = {"accept": "application/json"} - if body is not None: - headers["content-type"] = "application/json" - if dashboard_auth: - headers["cookie"] = f"botmux_dashboard_token={dashboard_auth}" - request = Request( - f"{endpoint}{path}", - data=body, - headers=headers, - method=method, - ) - try: - with _NO_REDIRECT_OPENER.open( # noqa: S310 - endpoint is explicit local-private operator configuration and redirects are disabled. - request, - timeout=timeout_seconds, - ) as response: - raw = response.read() - except HTTPError as exc: - try: - error_payload = json.loads(exc.read().decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError): - error_payload = {} - raise BotmuxApiError( - exc.code, - error_payload if isinstance(error_payload, Mapping) else {}, - ) from exc - except (URLError, TimeoutError, OSError) as exc: - raise BotmuxTransportError("botmux transport failed") from exc - try: - parsed = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise BotmuxTransportError("botmux returned a non-JSON response") from exc - if not isinstance(parsed, dict): - raise BotmuxTransportError("botmux returned an invalid JSON response") - return parsed - - -def _operation_packet( - *, - ok: bool, - goal_id: str, - operation: str, - execute: bool, - status: str, - public_summary: str, - blocker: str | None = None, - external_write_performed: bool = False, - readback_verified: bool = False, - idempotency_key: str | None = None, - receipt_id: str | None = None, - details: Mapping[str, Any] | None = None, -) -> dict[str, Any]: - packet: dict[str, Any] = { - "schema_version": BOTMUX_RUNTIME_OPERATION_SCHEMA_VERSION, - "ok": ok, - "goal_id": goal_id, - "provider": BOTMUX_PROVIDER, - "operation": operation, - "execute": execute, - "status": status, - "external_write_performed": external_write_performed, - "readback_verified": readback_verified, - "idempotency_key": idempotency_key, - "receipt_id": receipt_id, - "public_summary": public_summary, - "private_provider_payload_captured": False, - } - if blocker: - packet["blocker"] = blocker - if details: - packet["details"] = dict(details) - _assert_public_packet(packet) - return packet - - -def _assert_public_packet(packet: Mapping[str, Any]) -> None: - def visit(value: Any) -> None: - if isinstance(value, Mapping): - for key, child in value.items(): - if key in _PRIVATE_PACKET_KEYS: - raise ValueError( - f"public botmux packet contains private key `{key}`" - ) - visit(child) - elif isinstance(value, list): - for child in value: - visit(child) - - visit(packet) - - -def _lock_timeout_packet( - *, goal_id: str, operation: str, execute: bool, error: LockAcquireTimeoutError -) -> dict[str, Any]: - packet = _operation_packet( - ok=False, - goal_id=goal_id, - operation=operation, - execute=execute, - status="blocked", - blocker="botmux_runtime_lock_timeout", - public_summary="the botmux runtime binding is busy; inspect the lock holder and retry", - ) - packet.update(lock_timeout_error_fields(error)) - _assert_public_packet(packet) - return packet - - -def _probe_botmux( - *, - binding: Mapping[str, Any], - requester: JsonRequester, -) -> dict[str, Any]: - endpoint = _validated_endpoint(str(binding.get("endpoint") or "")) - bot_id = _validated_private_id(str(binding.get("bot_id") or ""), "bot id") - chat_id = _validated_private_id(str(binding.get("chat_id") or ""), "chat id") - expected_working_dir = _normalized_working_dir( - str(binding.get("expected_working_dir") or "") - ) - dashboard_auth = _dashboard_auth_for_binding(binding) - health = requester(endpoint=endpoint, path="/__health") - if health.get("ok") is not True: - raise ValueError("botmux health probe failed") - bots_payload = requester( - endpoint=endpoint, - path="/api/bots", - dashboard_auth=dashboard_auth, - ) - bots = bots_payload.get("bots") - bots = bots if isinstance(bots, list) else [] - selected = next( - ( - dict(item) - for item in bots - if isinstance(item, Mapping) - and str(item.get("larkAppId") or "") == bot_id - ), - None, - ) - if selected is None: - raise ValueError("configured botmux bot is not online") - if selected.get("online") is not True: - raise ValueError("configured botmux bot is offline") - groups_payload = requester( - endpoint=endpoint, - path="/api/groups", - dashboard_auth=dashboard_auth, - ) - chats = groups_payload.get("chats") - chats = chats if isinstance(chats, list) else [] - selected_chat = next( - ( - dict(item) - for item in chats - if isinstance(item, Mapping) - and str(item.get("chatId") or "") == chat_id - ), - None, - ) - if selected_chat is None: - raise ValueError("configured botmux chat is not visible") - member_bots = selected_chat.get("memberBots") - member_bots = member_bots if isinstance(member_bots, list) else [] - selected_member = next( - ( - dict(item) - for item in member_bots - if isinstance(item, Mapping) - and str(item.get("larkAppId") or "") == bot_id - and item.get("inChat") is True - ), - None, - ) - if selected_member is None: - raise ValueError("configured botmux bot is not in the selected chat") - oncall = selected_member.get("oncallChat") - oncall = oncall if isinstance(oncall, Mapping) else {} - configured_working_dirs = { - _normalized_working_dir(value) - for value in ( - str(selected.get("defaultWorkingDir") or ""), - str(oncall.get("workingDir") or ""), - ) - if value - } - if expected_working_dir not in configured_working_dirs: - raise ValueError( - "configured botmux bot or chat does not bind the LoopX project directory" - ) - route = requester( - endpoint=endpoint, - path="/api/trigger", - method="POST", - dashboard_auth=dashboard_auth, - payload={ - "source": {"type": "webhook"}, - "target": { - "kind": "turn", - "botId": bot_id, - "chatId": chat_id, - }, - "instruction": "LoopX botmux route readiness probe.", - "envelope": { - "format": "json", - "sourceName": "loopx", - "trusted": False, - }, - "options": {"dryRun": True}, - }, - ) - route_verified = bool( - route.get("ok") is True and str(route.get("action") or "") == "dry_run" - ) - if not route_verified: - raise ValueError("botmux did not verify the configured chat route") - return { - "health_verified": True, - "bot_online": True, - "project_working_dir_verified": True, - "chat_route_verified": True, - } - - -def _setup_botmux_runtime( - *, - registry: Mapping[str, Any], - registry_path: Path, - goal_id: str, - binding_path: Path, - endpoint: str, - bot_id: str, - chat_id: str, - token_env: str = BOTMUX_DEFAULT_TOKEN_ENV, - execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: - _goal_from_registry(registry, goal_id) - payload = read_botmux_runtime_binding(binding_path) - prior = botmux_binding_for_goal(payload, goal_id) or {} - endpoint = _validated_endpoint(endpoint) - bot_id = _validated_private_id(bot_id, "bot id") - chat_id = _validated_private_id(chat_id, "chat id") - token_env = _validated_token_env(token_env) - expected_working_dir = registry_project_root(registry_path) - same_route = bool( - prior.get("endpoint") == endpoint - and prior.get("bot_id") == bot_id - and prior.get("chat_id") == chat_id - and prior.get("token_env") == token_env - and prior.get("expected_working_dir") == str(expected_working_dir) - ) - binding = { - "goal_id": goal_id, - "provider": BOTMUX_PROVIDER, - "enabled": True, - "endpoint": endpoint, - "bot_id": bot_id, - "chat_id": chat_id, - "token_env": token_env, - "expected_working_dir": str(expected_working_dir), - "session": dict(prior.get("session") or {}) if same_route else {}, - "receipts": dict(prior.get("receipts") or {}) if same_route else {}, - } - try: - probe = _probe_botmux(binding=binding, requester=requester) - except ValueError as exc: - blocker = ( - "botmux_auth_unavailable" - if "token is unavailable" in str(exc) - else "botmux_configuration_invalid" - ) - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_setup", - execute=execute, - status="blocked", - blocker=blocker, - public_summary="the botmux runtime binding could not be verified", - ) - except BotmuxApiError: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_setup", - execute=execute, - status="blocked", - blocker="botmux_api_rejected", - public_summary="botmux rejected the runtime readiness probe", - ) - except BotmuxTransportError: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_setup", - execute=execute, - status="blocked", - blocker="botmux_unreachable", - public_summary="the configured botmux daemon is unreachable", - ) - if execute: - binding["verified_at"] = _now_iso() - _save_binding( - binding_path=binding_path, - payload=payload, - goal_id=goal_id, - binding=binding, - ) - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_setup", - execute=execute, - status="configured" if execute else "preview_ready", - public_summary=( - "configured the verified botmux runtime binding" - if execute - else "the botmux runtime binding is ready to configure" - ), - readback_verified=bool(execute), - details=probe, - ) +def _resolve_requester(requester: JsonRequester | None) -> JsonRequester: + return _request_json if requester is None else requester def doctor_botmux_runtime( *, goal_id: str, binding_path: Path, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: + requester: JsonRequester | None = None, +) -> Payload: + """Verify the active botmux daemon, bot, project cwd, and chat route.""" + active_requester = _resolve_requester(requester) try: with exclusive_file_lock(binding_path, operation="botmux_runtime_doctor"): - binding = botmux_binding_for_goal( - read_botmux_runtime_binding(binding_path), - goal_id, - ) - if binding is None or binding.get("enabled") is not True: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_doctor", - execute=False, - status="blocked", - blocker="botmux_binding_missing", - public_summary="configure a botmux runtime binding for this goal", - ) - try: - probe = _probe_botmux(binding=binding, requester=requester) - except (ValueError, BotmuxApiError, BotmuxTransportError) as exc: - if isinstance(exc, ValueError): - blocker = ( - "botmux_auth_unavailable" - if "token is unavailable" in str(exc) - else "botmux_configuration_invalid" - ) - summary = "the botmux runtime binding is not ready" - elif isinstance(exc, BotmuxApiError): - blocker = "botmux_api_rejected" - summary = "botmux rejected the runtime readiness probe" - else: - blocker = "botmux_unreachable" - summary = "the configured botmux daemon is unreachable" - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_doctor", - execute=False, - status="blocked", - blocker=blocker, - public_summary=summary, - ) - return _operation_packet( - ok=True, + return _doctor_botmux_runtime( goal_id=goal_id, - operation="runtime_doctor", - execute=False, - status="ready", - public_summary="the botmux runtime binding is ready", - readback_verified=True, - details=probe, + binding_path=binding_path, + requester=active_requester, ) except LockAcquireTimeoutError as exc: return _lock_timeout_packet( @@ -798,636 +153,9 @@ def doctor_botmux_runtime( ) -def _disable_botmux_runtime( - *, - goal_id: str, - binding_path: Path, - execute: bool = False, -) -> dict[str, Any]: - payload = read_botmux_runtime_binding(binding_path) - binding = botmux_binding_for_goal(payload, goal_id) - if binding is None: - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_disable", - execute=execute, - status="not_configured", - public_summary="no botmux runtime binding is configured for this goal", - ) - if execute: - binding["enabled"] = False - binding["session"] = {} - binding["disabled_at"] = _now_iso() - _save_binding( - binding_path=binding_path, - payload=payload, - goal_id=goal_id, - binding=binding, - ) - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_disable", - execute=execute, - status="disabled" if execute else "preview_ready", - public_summary=( - "disabled the botmux runtime binding for this goal" - if execute - else "the botmux runtime binding is ready to disable" - ), - readback_verified=bool(execute), - ) - - -def build_botmux_loopx_instruction(goal_id: str) -> str: - return ( - f"Continue the active LoopX goal `{goal_id}` in the current project using " - "the installed LoopX CLI or managed skill. Read canonical goal state and " - "execute the active next action. Complete a coherent artifact, targeted " - "validation, and state writeback. Continue the next bounded segment while " - "no explicit gate, quota, authority, or production access blocker applies. " - "When stopping, report the exact stop reason and a pasteable resume command." - ) - - -def goal_runtime_revision( - *, - registry: Mapping[str, Any], - registry_path: Path, - goal_id: str, -) -> str: - goal = _goal_from_registry(registry, goal_id) - raw_state_path = str(goal.get("state_file") or "").strip() - state_bytes = b"" - if raw_state_path: - state_path = Path(raw_state_path).expanduser() - if not state_path.is_absolute(): - state_path = registry_project_root(registry_path) / state_path - try: - state_bytes = state_path.read_bytes() - except OSError: - state_bytes = b"" - digest = hashlib.sha256( - goal_id.encode("utf-8") + b"\0" + state_bytes - ).hexdigest() - return digest[:24] - - -def _dispatch_key(*, goal_id: str, revision: str, instruction: str) -> str: - digest = hashlib.sha256( - json.dumps( - [goal_id, revision, instruction], - ensure_ascii=False, - separators=(",", ":"), - ).encode("utf-8") - ).hexdigest() - return f"sha256:{digest}" - - -def _provider_turn_key(dispatch_key: str) -> str: - return f"loopx-{dispatch_key.removeprefix('sha256:')[:32]}" - - -def _receipt_id(dispatch_key: str) -> str: - return f"runtime_{dispatch_key.removeprefix('sha256:')[:16]}" - - -def _trigger_botmux_runtime( - *, - registry: Mapping[str, Any], - registry_path: Path, - goal_id: str, - binding_path: Path, - instruction: str | None = None, - turn_key: str | None = None, - execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: - payload = read_botmux_runtime_binding(binding_path) - binding = botmux_binding_for_goal(payload, goal_id) - if binding is None or binding.get("enabled") is not True: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_trigger", - execute=execute, - status="blocked", - blocker="botmux_binding_missing", - public_summary="configure a botmux runtime binding for this goal", - ) - selected_instruction = str( - instruction or build_botmux_loopx_instruction(goal_id) - ).strip() - if not selected_instruction: - raise ValueError("botmux runtime instruction must not be empty") - revision = str( - turn_key - or goal_runtime_revision( - registry=registry, - registry_path=registry_path, - goal_id=goal_id, - ) - ) - dispatch_key = _dispatch_key( - goal_id=goal_id, - revision=revision, - instruction=selected_instruction, - ) - receipts = dict(binding.get("receipts") or {}) - prior = receipts.get(dispatch_key) - prior_state = ( - _dispatch_state(prior.get("state")) - if isinstance(prior, Mapping) - else None - ) - if prior_state in { - BotmuxDispatchState.ATTEMPTING, - BotmuxDispatchState.QUEUED, - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - BotmuxDispatchState.UNKNOWN, - }: - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_trigger", - execute=execute, - status="already_dispatched", - public_summary="the same botmux runtime turn was already dispatched", - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - details={ - "dispatch_state": prior_state.value, - "session_reused": True, - }, - ) - session = dict(binding.get("session") or {}) - existing_session_id = str(session.get("session_id") or "").strip() - if not execute: - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_trigger", - execute=False, - status="preview_ready", - public_summary="the next LoopX turn is ready for botmux dispatch", - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - details={ - "dispatch_state": "preview", - "session_reused": bool(existing_session_id), - }, - ) - endpoint = _validated_endpoint(str(binding.get("endpoint") or "")) - bot_id = _validated_private_id(str(binding.get("bot_id") or ""), "bot id") - dashboard_auth = _dashboard_auth_for_binding(binding) - target: dict[str, Any] = {"kind": "turn", "botId": bot_id} - options: dict[str, Any] = {"asyncReturnSessionId": True} - if existing_session_id: - target["sessionId"] = _validated_private_id( - existing_session_id, - "session id", - ) - options["turnIdempotencyKey"] = _provider_turn_key(dispatch_key) - else: - target["chatId"] = _validated_private_id( - str(binding.get("chat_id") or ""), - "chat id", - ) - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.ATTEMPTING, - timestamp_field="attempted_at", - updates={"session_reused": bool(existing_session_id)}, - session={ - **( - {"session_id": existing_session_id} - if existing_session_id - else {} - ), - "active_dispatch_key": dispatch_key, - "updated_at": _now_iso(), - }, - ) - try: - response = requester( - endpoint=endpoint, - path="/api/trigger", - method="POST", - dashboard_auth=dashboard_auth, - payload={ - "source": {"type": "webhook"}, - "target": target, - "instruction": selected_instruction, - "envelope": { - "format": "json", - "sourceName": "loopx", - "trusted": False, - }, - "options": options, - }, - ) - except BotmuxTransportError: - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.UNKNOWN, - timestamp_field="unknown_at", - updates={"unknown_reason": "transport_failure"}, - ) - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_trigger", - execute=True, - status="dispatch_unknown", - blocker="botmux_dispatch_outcome_unknown", - public_summary=( - "botmux dispatch outcome is unknown; inspect the existing receipt " - "before retrying" - ), - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - ) - except BotmuxApiError as exc: - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.REJECTED, - timestamp_field="rejected_at", - updates={"http_status": exc.status}, - ) - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_trigger", - execute=True, - status="rejected", - blocker="botmux_api_rejected", - public_summary="botmux rejected the LoopX runtime turn", - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - ) - response_target = response.get("target") - response_target = ( - response_target if isinstance(response_target, Mapping) else {} - ) - async_payload = response.get("async") - async_payload = async_payload if isinstance(async_payload, Mapping) else {} - session_id = str( - response_target.get("sessionId") or async_payload.get("sessionId") or "" - ).strip() - if response.get("ok") is not True or not session_id: - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.UNKNOWN, - timestamp_field="unknown_at", - updates={"unknown_reason": "invalid_provider_receipt"}, - ) - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_trigger", - execute=True, - status="dispatch_unknown", - blocker="botmux_dispatch_receipt_invalid", - public_summary="botmux did not return a verifiable runtime session receipt", - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - ) - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.QUEUED, - timestamp_field="queued_at", - updates={ - "session_id": session_id, - "trigger_id": str(response.get("triggerId") or ""), - }, - session={ - "session_id": session_id, - "active_dispatch_key": dispatch_key, - "updated_at": _now_iso(), - }, - ) - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_trigger", - execute=True, - status="queued", - public_summary="queued one LoopX turn through the botmux runtime", - external_write_performed=True, - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - details={"dispatch_state": "queued", "session_reused": bool(existing_session_id)}, - ) - - -def _status_botmux_runtime( - *, - goal_id: str, - binding_path: Path, - execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: - payload = read_botmux_runtime_binding(binding_path) - binding = botmux_binding_for_goal(payload, goal_id) - if binding is None: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status="blocked", - blocker="botmux_binding_missing", - public_summary="configure a botmux runtime binding for this goal", - ) - session = dict(binding.get("session") or {}) - session_id = str(session.get("session_id") or "").strip() - dispatch_key = str(session.get("active_dispatch_key") or "").strip() - # A reused session's trigger-result describes its latest *accepted* turn. - # A dispatch the provider never accepted cannot be vouched for by it: - # ATTEMPTING and REJECTED never became one, and an UNKNOWN that was never - # QUEUED (an interrupted attempt, a transport failure or an unverifiable - # receipt) is not one either, so a repeated status must not adopt the - # previous turn's result for it. Resolve these from the local receipt alone. - # An UNKNOWN that was QUEUED and only lost its status read still recovers - # through the provider. - local_receipts = binding.get("receipts") - local_receipt = ( - local_receipts.get(dispatch_key) if isinstance(local_receipts, Mapping) else None - ) - local_state = _dispatch_state( - local_receipt.get("state") if isinstance(local_receipt, Mapping) else None - ) - unaccepted_dispatch = bool(dispatch_key) and ( - local_state in {BotmuxDispatchState.ATTEMPTING, BotmuxDispatchState.REJECTED} - or ( - local_state == BotmuxDispatchState.UNKNOWN - and isinstance(local_receipt, Mapping) - and not local_receipt.get("queued_at") - ) - ) - if not session_id or not dispatch_key or unaccepted_dispatch: - active = _active_dispatch_receipt(binding) - if active is not None: - active_key, receipt = active - receipt_state = _dispatch_state(receipt.get("state")) - if receipt_state == BotmuxDispatchState.ATTEMPTING: - receipt_state = BotmuxDispatchState.UNKNOWN - if execute: - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=active_key, - state=BotmuxDispatchState.UNKNOWN, - timestamp_field="unknown_at", - updates={"unknown_reason": "unresolved_attempt"}, - ) - if receipt_state in { - BotmuxDispatchState.UNKNOWN, - BotmuxDispatchState.REJECTED, - }: - public_state = receipt_state.value - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status=public_state, - blocker=( - "botmux_dispatch_outcome_unknown" - if receipt_state == BotmuxDispatchState.UNKNOWN - else "botmux_api_rejected" - ), - public_summary=( - "the botmux runtime dispatch outcome is unknown" - if receipt_state == BotmuxDispatchState.UNKNOWN - else "the botmux runtime dispatch was rejected" - ), - idempotency_key=active_key, - receipt_id=_receipt_id(active_key), - details={ - "dispatch_state": public_state, - "output_available": False, - "local_receipt_updated": bool( - execute - and _dispatch_state(receipt.get("state")) - == BotmuxDispatchState.ATTEMPTING - ), - }, - ) - return _operation_packet( - ok=True, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status="idle", - public_summary="no botmux runtime turn has been dispatched for this goal", - details={"dispatch_state": "idle", "output_available": False}, - ) - # The session's trigger-result without a trigger id is its latest turn, - # which another client may have started. Ask for the id this receipt was - # queued under, and promote nothing the provider does not attribute to it. - stored_trigger_id = ( - str(local_receipt.get("trigger_id") or "").strip() - if isinstance(local_receipt, Mapping) - else "" - ) - try: - pinned_trigger_id: str | None = _validated_private_id(stored_trigger_id, "trigger id") - except ValueError: - pinned_trigger_id = None - session_level_missing = False - try: - if pinned_trigger_id is None: - result = {"state": BotmuxDispatchState.UNKNOWN.value} - else: - result = requester( - endpoint=_validated_endpoint(str(binding.get("endpoint") or "")), - path=( - "/api/sessions/" - f"{quote(_validated_private_id(session_id, 'session id'), safe='')}" - f"/trigger-result?triggerId={quote(pinned_trigger_id, safe='')}" - ), - dashboard_auth=_dashboard_auth_for_binding(binding), - ) - except ValueError: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status="blocked", - blocker="botmux_auth_unavailable", - public_summary="the botmux runtime status cannot be read without auth", - ) - except BotmuxApiError as exc: - if exc.status == 404 and ( - exc.payload.get("error") == "unknown_session" - or exc.payload.get("state") == "not_found" - ): - result = {"state": "not_found"} - echoed_trigger_id = str(exc.payload.get("triggerId") or "").strip() - if echoed_trigger_id: - result["triggerId"] = echoed_trigger_id - # Only an explicit "this session is gone" that names no turn cannot - # be attributed to another one. A generic 404, or one that names a - # turn, is checked like any other response. - session_level_missing = ( - exc.payload.get("error") == "unknown_session" and not echoed_trigger_id - ) - else: - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status="blocked", - blocker="botmux_api_rejected", - public_summary="botmux rejected the runtime status read", - ) - except BotmuxTransportError: - if execute: - receipts = binding.get("receipts") - receipts = receipts if isinstance(receipts, Mapping) else {} - receipt = receipts.get(dispatch_key) - current_state = ( - _dispatch_state(receipt.get("state")) - if isinstance(receipt, Mapping) - else None - ) - if current_state in { - BotmuxDispatchState.QUEUED, - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.UNKNOWN, - }: - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=BotmuxDispatchState.UNKNOWN, - timestamp_field="unknown_at", - updates={"unknown_reason": "status_transport_failure"}, - ) - return _operation_packet( - ok=False, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status="unknown", - blocker="botmux_unreachable", - public_summary="the botmux runtime status is temporarily unknown", - ) - provider_state = _dispatch_state(result.get("state")) - if provider_state not in { - BotmuxDispatchState.RUNNING, - BotmuxDispatchState.COMPLETED, - BotmuxDispatchState.FAILED, - BotmuxDispatchState.NOT_FOUND, - }: - provider_state = BotmuxDispatchState.UNKNOWN - identity_unverified = pinned_trigger_id is None - if ( - pinned_trigger_id is not None - and not session_level_missing - and str(result.get("triggerId") or "").strip() != pinned_trigger_id - ): - # The provider answered for a different turn, or did not say which. - provider_state = BotmuxDispatchState.UNKNOWN - identity_unverified = True - latest_payload = read_botmux_runtime_binding(binding_path) - latest_binding = botmux_binding_for_goal(latest_payload, goal_id) or binding - latest_receipts = latest_binding.get("receipts") - latest_receipts = ( - latest_receipts if isinstance(latest_receipts, Mapping) else {} - ) - latest_receipt = latest_receipts.get(dispatch_key) - local_state = ( - _dispatch_state(latest_receipt.get("state")) - if isinstance(latest_receipt, Mapping) - else None - ) - provider_observation_ignored = ( - local_state in _TERMINAL_DISPATCH_STATES - and provider_state != local_state - ) - state = local_state if provider_observation_ignored else provider_state - output = result.get("output") - output_available = not identity_unverified and bool( - isinstance(output, Mapping) and str(output.get("content") or "").strip() - ) - local_receipt_updated = execute - if execute: - updates = None - if identity_unverified and state == BotmuxDispatchState.UNKNOWN: - updates = {"unknown_reason": "trigger_identity_unverified"} - if provider_observation_ignored: - updates = { - "provider_observation": provider_state.value, - "provider_observation_ignored": True, - } - _persist_dispatch_receipt( - binding_path=binding_path, - goal_id=goal_id, - binding=binding, - dispatch_key=dispatch_key, - state=state, - timestamp_field="status_checked_at", - updates=updates, - ) - details: dict[str, Any] = { - "dispatch_state": state.value, - "output_available": output_available, - "local_receipt_updated": local_receipt_updated, - } - if provider_observation_ignored: - details.update( - { - "provider_observation": provider_state.value, - "provider_observation_ignored": True, - } - ) - return _operation_packet( - ok=state != BotmuxDispatchState.UNKNOWN, - goal_id=goal_id, - operation="runtime_status", - execute=execute, - status=state.value, - blocker=( - "botmux_status_unknown" - if state == BotmuxDispatchState.UNKNOWN - else None - ), - public_summary=f"the botmux runtime turn is {state.value}", - readback_verified=state == BotmuxDispatchState.COMPLETED, - idempotency_key=dispatch_key, - receipt_id=_receipt_id(dispatch_key), - details=details, - ) - - def setup_botmux_runtime( *, - registry: Mapping[str, Any], + registry: PayloadView, registry_path: Path, goal_id: str, binding_path: Path, @@ -1436,8 +164,10 @@ def setup_botmux_runtime( chat_id: str, token_env: str = BOTMUX_DEFAULT_TOKEN_ENV, execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: + requester: JsonRequester | None = None, +) -> Payload: + """Verify and optionally bind a Goal to a botmux bot and chat route.""" + active_requester = _resolve_requester(requester) if not execute: return _setup_botmux_runtime( registry=registry, @@ -1449,7 +179,9 @@ def setup_botmux_runtime( chat_id=chat_id, token_env=token_env, execute=False, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) with exclusive_file_lock(binding_path, operation="botmux_runtime_setup"): return _setup_botmux_runtime( @@ -1462,7 +194,9 @@ def setup_botmux_runtime( chat_id=chat_id, token_env=token_env, execute=True, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) @@ -1471,32 +205,39 @@ def disable_botmux_runtime( goal_id: str, binding_path: Path, execute: bool = False, -) -> dict[str, Any]: +) -> Payload: + """Disable one Goal's botmux runtime binding (preview unless ``execute=True``).""" if not execute: return _disable_botmux_runtime( goal_id=goal_id, binding_path=binding_path, execute=False, + writer=_atomic_write, + now_iso=_current_iso, ) with exclusive_file_lock(binding_path, operation="botmux_runtime_disable"): return _disable_botmux_runtime( goal_id=goal_id, binding_path=binding_path, execute=True, + writer=_atomic_write, + now_iso=_current_iso, ) def trigger_botmux_runtime( *, - registry: Mapping[str, Any], + registry: PayloadView, registry_path: Path, goal_id: str, binding_path: Path, instruction: str | None = None, turn_key: str | None = None, execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: + requester: JsonRequester | None = None, +) -> Payload: + """Preview or queue one idempotent LoopX turn through the bound botmux runtime.""" + active_requester = _resolve_requester(requester) if not execute: return _trigger_botmux_runtime( registry=registry, @@ -1506,7 +247,9 @@ def trigger_botmux_runtime( instruction=instruction, turn_key=turn_key, execute=False, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) with exclusive_file_lock(binding_path, operation="botmux_runtime_trigger"): return _trigger_botmux_runtime( @@ -1517,7 +260,9 @@ def trigger_botmux_runtime( instruction=instruction, turn_key=turn_key, execute=True, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) @@ -1526,15 +271,19 @@ def status_botmux_runtime( goal_id: str, binding_path: Path, execute: bool = False, - requester: JsonRequester = _request_json, -) -> dict[str, Any]: + requester: JsonRequester | None = None, +) -> Payload: + """Inspect and optionally persist the current botmux runtime dispatch state.""" + active_requester = _resolve_requester(requester) if execute: with exclusive_file_lock(binding_path, operation="botmux_runtime_status"): return _status_botmux_runtime( goal_id=goal_id, binding_path=binding_path, execute=True, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) try: with exclusive_file_lock(binding_path, operation="botmux_runtime_status"): @@ -1542,13 +291,11 @@ def status_botmux_runtime( goal_id=goal_id, binding_path=binding_path, execute=False, - requester=requester, + requester=active_requester, + writer=_atomic_write, + now_iso=_current_iso, ) except LockAcquireTimeoutError as exc: return _lock_timeout_packet( goal_id=goal_id, operation="runtime_status", execute=False, error=exc ) - - -def _now_iso() -> str: - return datetime.now(timezone.utc).isoformat() diff --git a/loopx/control_plane/goals/botmux_status.py b/loopx/control_plane/goals/botmux_status.py new file mode 100644 index 0000000000..c701f82dec --- /dev/null +++ b/loopx/control_plane/goals/botmux_status.py @@ -0,0 +1,411 @@ +"""Receipt-bound status polling and terminal readback preservation for botmux.""" + +from __future__ import annotations + +from pathlib import Path +from urllib.parse import quote + +from .botmux_binding_store import ( + _TERMINAL_DISPATCH_STATES, + AtomicJsonWriter, + BotmuxApiError, + BotmuxDispatchState, + BotmuxTransportError, + JsonRequester, + NowIsoFn, + Payload, + PayloadView, + _active_dispatch_receipt, + _as_mapping, + _as_mutable_dict, + _dispatch_state, + _now_iso, + _operation_packet, + _persist_dispatch_receipt, + botmux_binding_for_goal, + read_botmux_runtime_binding, +) +from .botmux_lifecycle import _receipt_id +from .botmux_transport import ( + _dashboard_auth_for_binding, + _validated_endpoint, + _validated_private_id, +) + +_PROVIDER_OBSERVABLE_STATES = frozenset( + { + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + } +) + + +def _resolve_unaccepted_dispatch_status( + *, + binding_path: Path, + goal_id: str, + binding: Payload, + execute: bool, + writer: AtomicJsonWriter, + now_iso: NowIsoFn, +) -> Payload: + active = _active_dispatch_receipt(binding) + if active is not None: + active_key, receipt = active + initial_state = _dispatch_state(receipt.get("state")) + receipt_state = initial_state + if receipt_state == BotmuxDispatchState.ATTEMPTING: + receipt_state = BotmuxDispatchState.UNKNOWN + if execute: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=active_key, + state=BotmuxDispatchState.UNKNOWN, + timestamp_field="unknown_at", + updates={"unknown_reason": "unresolved_attempt"}, + writer=writer, + now_iso=now_iso, + ) + if receipt_state in { + BotmuxDispatchState.UNKNOWN, + BotmuxDispatchState.REJECTED, + }: + public_state = receipt_state.value + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status=public_state, + blocker=( + "botmux_dispatch_outcome_unknown" + if receipt_state == BotmuxDispatchState.UNKNOWN + else "botmux_api_rejected" + ), + public_summary=( + "the botmux runtime dispatch outcome is unknown" + if receipt_state == BotmuxDispatchState.UNKNOWN + else "the botmux runtime dispatch was rejected" + ), + idempotency_key=active_key, + receipt_id=_receipt_id(active_key), + details={ + "dispatch_state": public_state, + "output_available": False, + "local_receipt_updated": bool( + execute and initial_state == BotmuxDispatchState.ATTEMPTING + ), + }, + ) + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status="idle", + public_summary="no botmux runtime turn has been dispatched for this goal", + details={"dispatch_state": "idle", "output_available": False}, + ) + + +def _record_status_transport_failure( + *, + binding_path: Path, + goal_id: str, + binding: Payload, + dispatch_key: str, + execute: bool, + writer: AtomicJsonWriter, + now_iso: NowIsoFn, +) -> Payload: + if execute: + receipts = _as_mapping(binding.get("receipts")) or {} + receipt = _as_mapping(receipts.get(dispatch_key)) + current_state = _dispatch_state( + receipt.get("state") if receipt is not None else None + ) + if current_state in { + BotmuxDispatchState.QUEUED, + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.UNKNOWN, + }: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.UNKNOWN, + timestamp_field="unknown_at", + updates={"unknown_reason": "status_transport_failure"}, + writer=writer, + now_iso=now_iso, + ) + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status="unknown", + blocker="botmux_unreachable", + public_summary="the botmux runtime status is temporarily unknown", + ) + + +def _query_pinned_trigger_status( + *, + binding_path: Path, + goal_id: str, + binding: Payload, + session_id: str, + dispatch_key: str, + pinned_trigger_id: str | None, + execute: bool, + requester: JsonRequester, + writer: AtomicJsonWriter, + now_iso: NowIsoFn, +) -> tuple[PayloadView | None, bool, Payload | None]: + if pinned_trigger_id is None: + return {"state": BotmuxDispatchState.UNKNOWN.value}, False, None + try: + result = requester( + endpoint=_validated_endpoint(str(binding.get("endpoint") or "")), + path=( + "/api/sessions/" + f"{quote(_validated_private_id(session_id, 'session id'), safe='')}" + f"/trigger-result?triggerId={quote(pinned_trigger_id, safe='')}" + ), + dashboard_auth=_dashboard_auth_for_binding(binding), + ) + return result, False, None + except ValueError: + return ( + None, + False, + _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status="blocked", + blocker="botmux_auth_unavailable", + public_summary="the botmux runtime status cannot be read without auth", + ), + ) + except BotmuxApiError as exc: + if exc.status == 404 and ( + exc.payload.get("error") == "unknown_session" + or exc.payload.get("state") == "not_found" + ): + not_found_result: Payload = {"state": "not_found"} + echoed_trigger_id = str(exc.payload.get("triggerId") or "").strip() + if echoed_trigger_id: + not_found_result["triggerId"] = echoed_trigger_id + # Only an explicit "this session is gone" that names no turn cannot + # be attributed to another one. + session_level_missing = ( + exc.payload.get("error") == "unknown_session" + and not echoed_trigger_id + ) + return not_found_result, session_level_missing, None + return ( + None, + False, + _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status="blocked", + blocker="botmux_api_rejected", + public_summary="botmux rejected the runtime status read", + ), + ) + except BotmuxTransportError: + return ( + None, + False, + _record_status_transport_failure( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + execute=execute, + writer=writer, + now_iso=now_iso, + ), + ) + + +def _resolve_observed_state( + *, + local_state: BotmuxDispatchState | None, + provider_state: BotmuxDispatchState, +) -> tuple[BotmuxDispatchState, bool]: + if ( + local_state is not None + and local_state in _TERMINAL_DISPATCH_STATES + and provider_state != local_state + ): + return local_state, True + return provider_state, False + + +def _status_botmux_runtime( + *, + goal_id: str, + binding_path: Path, + execute: bool = False, + requester: JsonRequester, + writer: AtomicJsonWriter, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + payload = read_botmux_runtime_binding(binding_path) + binding = botmux_binding_for_goal(payload, goal_id) + if binding is None: + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status="blocked", + blocker="botmux_binding_missing", + public_summary="configure a botmux runtime binding for this goal", + ) + session = _as_mutable_dict(binding.get("session")) + session_id = str(session.get("session_id") or "").strip() + dispatch_key = str(session.get("active_dispatch_key") or "").strip() + local_receipts = _as_mapping(binding.get("receipts")) + local_receipt = ( + _as_mapping(local_receipts.get(dispatch_key)) + if (local_receipts is not None and dispatch_key) + else None + ) + local_state = _dispatch_state( + local_receipt.get("state") if local_receipt is not None else None + ) + unaccepted_dispatch = bool(dispatch_key) and ( + local_state in {BotmuxDispatchState.ATTEMPTING, BotmuxDispatchState.REJECTED} + or ( + local_state == BotmuxDispatchState.UNKNOWN + and local_receipt is not None + and not local_receipt.get("queued_at") + ) + ) + if not session_id or not dispatch_key or unaccepted_dispatch: + return _resolve_unaccepted_dispatch_status( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + execute=execute, + writer=writer, + now_iso=now_iso, + ) + # Ask for the trigger id this receipt was queued under, and promote nothing + # the provider does not attribute to it. + stored_trigger_id = ( + str(local_receipt.get("trigger_id") or "").strip() + if local_receipt is not None + else "" + ) + try: + pinned_trigger_id: str | None = _validated_private_id( + stored_trigger_id, "trigger id" + ) + except ValueError: + pinned_trigger_id = None + result, session_level_missing, error_packet = _query_pinned_trigger_status( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + session_id=session_id, + dispatch_key=dispatch_key, + pinned_trigger_id=pinned_trigger_id, + execute=execute, + requester=requester, + writer=writer, + now_iso=now_iso, + ) + if error_packet is not None or result is None: + assert error_packet is not None + return error_packet + raw_provider_state = _dispatch_state(result.get("state")) + provider_state = ( + raw_provider_state + if raw_provider_state in _PROVIDER_OBSERVABLE_STATES + else BotmuxDispatchState.UNKNOWN + ) + identity_unverified = pinned_trigger_id is None + if ( + pinned_trigger_id is not None + and not session_level_missing + and str(result.get("triggerId") or "").strip() != pinned_trigger_id + ): + provider_state = BotmuxDispatchState.UNKNOWN + identity_unverified = True + latest_payload = read_botmux_runtime_binding(binding_path) + latest_binding = botmux_binding_for_goal(latest_payload, goal_id) or binding + latest_receipts = _as_mapping(latest_binding.get("receipts")) or {} + latest_receipt = _as_mapping(latest_receipts.get(dispatch_key)) + latest_local_state = _dispatch_state( + latest_receipt.get("state") if latest_receipt is not None else None + ) + state, provider_observation_ignored = _resolve_observed_state( + local_state=latest_local_state, + provider_state=provider_state, + ) + output = _as_mapping(result.get("output")) + output_available = not identity_unverified and bool( + output is not None and str(output.get("content") or "").strip() + ) + local_receipt_updated = execute + if execute: + updates: Payload | None = None + if identity_unverified and state == BotmuxDispatchState.UNKNOWN: + updates = {"unknown_reason": "trigger_identity_unverified"} + if provider_observation_ignored: + updates = { + "provider_observation": provider_state.value, + "provider_observation_ignored": True, + } + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=state, + timestamp_field="status_checked_at", + updates=updates, + writer=writer, + now_iso=now_iso, + ) + details: Payload = { + "dispatch_state": state.value, + "output_available": output_available, + "local_receipt_updated": local_receipt_updated, + } + if provider_observation_ignored: + details.update( + { + "provider_observation": provider_state.value, + "provider_observation_ignored": True, + } + ) + return _operation_packet( + ok=state != BotmuxDispatchState.UNKNOWN, + goal_id=goal_id, + operation="runtime_status", + execute=execute, + status=state.value, + blocker=( + "botmux_status_unknown" if state == BotmuxDispatchState.UNKNOWN else None + ), + public_summary=f"the botmux runtime turn is {state.value}", + readback_verified=state == BotmuxDispatchState.COMPLETED, + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + details=details, + ) diff --git a/loopx/control_plane/goals/botmux_transport.py b/loopx/control_plane/goals/botmux_transport.py new file mode 100644 index 0000000000..e70b63a61f --- /dev/null +++ b/loopx/control_plane/goals/botmux_transport.py @@ -0,0 +1,302 @@ +"""HTTP transport, SSRF/config validation, and readiness probing for botmux.""" + +from __future__ import annotations + +import ipaddress +import json +import os +from collections.abc import Mapping +from http.client import HTTPMessage +from pathlib import Path +from typing import IO, cast +from urllib.error import HTTPError, URLError +from urllib.parse import urlparse +from urllib.request import HTTPRedirectHandler, Request, build_opener + +from ...public_safe_text import OPAQUE_ID_PATTERN as _SAFE_TOKEN +from .botmux_binding_store import ( + BOTMUX_HTTP_TIMEOUT_SECONDS, + BotmuxApiError, + BotmuxTransportError, + JsonRequester, + Payload, + PayloadView, + _ENV_NAME, + _as_mapping, + _as_string_dict, +) + + +class _NoRedirectHandler(HTTPRedirectHandler): + """Refuse HTTP redirects so loopback/HTTPS trust stays pinned.""" + + def redirect_request( + self, + req: Request, + fp: IO[bytes], + code: int, + msg: str, + headers: HTTPMessage, + newurl: str, + ) -> Request | None: + return None + + +_NO_REDIRECT_OPENER = build_opener(_NoRedirectHandler()) + + +def _validated_endpoint(value: str) -> str: + endpoint = str(value or "").strip().rstrip("/") + parsed = urlparse(endpoint) + if ( + parsed.scheme not in {"http", "https"} + or not parsed.hostname + or parsed.username + or parsed.password + or parsed.query + or parsed.fragment + or parsed.path not in {"", "/"} + ): + raise ValueError("botmux endpoint must be one HTTP(S) origin") + if parsed.scheme == "http": + hostname = str(parsed.hostname or "").lower() + try: + is_loopback = ipaddress.ip_address(hostname).is_loopback + except ValueError: + is_loopback = hostname == "localhost" + if not is_loopback: + raise ValueError("remote botmux endpoint must use HTTPS") + return endpoint + + +def _validated_token_env(value: str) -> str: + token_env = str(value or "").strip() + if not _ENV_NAME.fullmatch(token_env): + raise ValueError("botmux token env must be one environment variable name") + return token_env + + +def _validated_private_id(value: str, label: str) -> str: + normalized = str(value or "").strip() + if not _SAFE_TOKEN.fullmatch(normalized): + raise ValueError(f"botmux {label} is invalid") + return normalized + + +def _normalized_working_dir(value: str) -> Path: + working_dir = Path(str(value or "").strip()).expanduser() + if not str(value or "").strip() or not working_dir.is_absolute(): + raise ValueError("botmux working directory must be absolute") + return working_dir.resolve() + + +def _dashboard_auth_for_binding(binding: PayloadView) -> str: + token_env = _validated_token_env(str(binding.get("token_env") or "")) + token = str(os.environ.get(token_env) or "").strip() + if not token or any(ord(character) <= 32 for character in token) or ";" in token: + raise ValueError("botmux dashboard token is unavailable") + return token + + +def _decode_json_object(raw: bytes) -> Payload: + try: + parsed = cast(object, json.loads(raw.decode("utf-8"))) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise BotmuxTransportError("botmux returned a non-JSON response") from exc + payload = _as_string_dict(parsed) + if payload is None: + raise BotmuxTransportError("botmux returned an invalid JSON response") + return payload + + +def _request_json( + *, + endpoint: str, + path: str, + method: str = "GET", + dashboard_auth: str | None = None, + payload: PayloadView | None = None, + timeout_seconds: float = BOTMUX_HTTP_TIMEOUT_SECONDS, +) -> Payload: + body = ( + json.dumps(dict(payload), ensure_ascii=False, separators=(",", ":")).encode( + "utf-8" + ) + if payload is not None + else None + ) + headers = {"accept": "application/json"} + if body is not None: + headers["content-type"] = "application/json" + if dashboard_auth: + headers["cookie"] = f"botmux_dashboard_token={dashboard_auth}" + request = Request( + f"{endpoint}{path}", + data=body, + headers=headers, + method=method, + ) + try: + with _NO_REDIRECT_OPENER.open( # noqa: S310 - endpoint is explicit local-private operator configuration and redirects are disabled. + request, + timeout=timeout_seconds, + ) as response: + raw = cast(bytes, response.read()) + except HTTPError as exc: + try: + raw_error = cast(object, json.loads(exc.read().decode("utf-8"))) + except (UnicodeDecodeError, json.JSONDecodeError): + raw_error = {} + error_payload = ( + cast(PayloadView, raw_error) if isinstance(raw_error, Mapping) else {} + ) + raise BotmuxApiError(exc.code, error_payload) from exc + except (URLError, TimeoutError, OSError) as exc: + raise BotmuxTransportError("botmux transport failed") from exc + return _decode_json_object(raw) + + +def _select_online_bot( + *, + endpoint: str, + dashboard_auth: str, + bot_id: str, + requester: JsonRequester, +) -> Payload: + bots_payload = requester( + endpoint=endpoint, + path="/api/bots", + dashboard_auth=dashboard_auth, + ) + raw_bots = bots_payload.get("bots") + bots = cast(list[object], raw_bots) if isinstance(raw_bots, list) else [] + selected: Payload | None = None + for item in bots: + mapping = _as_mapping(item) + if mapping is not None and str(mapping.get("larkAppId") or "") == bot_id: + selected = dict(mapping) + break + if selected is None: + raise ValueError("configured botmux bot is not online") + if selected.get("online") is not True: + raise ValueError("configured botmux bot is offline") + return selected + + +def _verify_chat_membership_and_cwd( + *, + endpoint: str, + dashboard_auth: str, + bot_id: str, + chat_id: str, + expected_working_dir: Path, + selected_bot: PayloadView, + requester: JsonRequester, +) -> None: + groups_payload = requester( + endpoint=endpoint, + path="/api/groups", + dashboard_auth=dashboard_auth, + ) + raw_chats = groups_payload.get("chats") + chats = cast(list[object], raw_chats) if isinstance(raw_chats, list) else [] + selected_chat: Payload | None = None + for item in chats: + mapping = _as_mapping(item) + if mapping is not None and str(mapping.get("chatId") or "") == chat_id: + selected_chat = dict(mapping) + break + if selected_chat is None: + raise ValueError("configured botmux chat is not visible") + raw_members = selected_chat.get("memberBots") + members = cast(list[object], raw_members) if isinstance(raw_members, list) else [] + selected_member: Payload | None = None + for item in members: + mapping = _as_mapping(item) + if ( + mapping is not None + and str(mapping.get("larkAppId") or "") == bot_id + and mapping.get("inChat") is True + ): + selected_member = dict(mapping) + break + if selected_member is None: + raise ValueError("configured botmux bot is not in the selected chat") + oncall = _as_mapping(selected_member.get("oncallChat")) or {} + configured_working_dirs = { + _normalized_working_dir(value) + for value in ( + str(selected_bot.get("defaultWorkingDir") or ""), + str(oncall.get("workingDir") or ""), + ) + if value + } + if expected_working_dir not in configured_working_dirs: + raise ValueError( + "configured botmux bot or chat does not bind the LoopX project directory" + ) + + +def _probe_botmux( + *, + binding: PayloadView, + requester: JsonRequester, +) -> Payload: + """Verify botmux liveness, bot online state, project cwd, and dry-run route.""" + endpoint = _validated_endpoint(str(binding.get("endpoint") or "")) + bot_id = _validated_private_id(str(binding.get("bot_id") or ""), "bot id") + chat_id = _validated_private_id(str(binding.get("chat_id") or ""), "chat id") + expected_working_dir = _normalized_working_dir( + str(binding.get("expected_working_dir") or "") + ) + dashboard_auth = _dashboard_auth_for_binding(binding) + health = requester(endpoint=endpoint, path="/__health") + if health.get("ok") is not True: + raise ValueError("botmux health probe failed") + selected_bot = _select_online_bot( + endpoint=endpoint, + dashboard_auth=dashboard_auth, + bot_id=bot_id, + requester=requester, + ) + _verify_chat_membership_and_cwd( + endpoint=endpoint, + dashboard_auth=dashboard_auth, + bot_id=bot_id, + chat_id=chat_id, + expected_working_dir=expected_working_dir, + selected_bot=selected_bot, + requester=requester, + ) + route = requester( + endpoint=endpoint, + path="/api/trigger", + method="POST", + dashboard_auth=dashboard_auth, + payload={ + "source": {"type": "webhook"}, + "target": { + "kind": "turn", + "botId": bot_id, + "chatId": chat_id, + }, + "instruction": "LoopX botmux route readiness probe.", + "envelope": { + "format": "json", + "sourceName": "loopx", + "trusted": False, + }, + "options": {"dryRun": True}, + }, + ) + route_verified = bool( + route.get("ok") is True and str(route.get("action") or "") == "dry_run" + ) + if not route_verified: + raise ValueError("botmux did not verify the configured chat route") + return { + "health_verified": True, + "bot_online": True, + "project_working_dir_verified": True, + "chat_route_verified": True, + } diff --git a/loopx/control_plane/goals/botmux_trigger.py b/loopx/control_plane/goals/botmux_trigger.py new file mode 100644 index 0000000000..47f786576f --- /dev/null +++ b/loopx/control_plane/goals/botmux_trigger.py @@ -0,0 +1,316 @@ +"""Idempotent LoopX turn dispatch for a configured botmux Goal Channel binding.""" + +from __future__ import annotations + +from pathlib import Path + +from .botmux_binding_store import ( + AtomicJsonWriter, + BotmuxApiError, + BotmuxDispatchState, + BotmuxTransportError, + JsonRequester, + NowIsoFn, + Payload, + PayloadView, + _as_mapping, + _as_mutable_dict, + _dispatch_state, + _now_iso, + _operation_packet, + _persist_dispatch_receipt, + botmux_binding_for_goal, + read_botmux_runtime_binding, +) +from .botmux_lifecycle import ( + _dispatch_key, + _provider_turn_key, + _receipt_id, + build_botmux_loopx_instruction, + goal_runtime_revision, +) +from .botmux_transport import ( + _dashboard_auth_for_binding, + _validated_endpoint, + _validated_private_id, +) + +_ALREADY_DISPATCHED_STATES = frozenset( + { + BotmuxDispatchState.ATTEMPTING, + BotmuxDispatchState.QUEUED, + BotmuxDispatchState.RUNNING, + BotmuxDispatchState.COMPLETED, + BotmuxDispatchState.FAILED, + BotmuxDispatchState.NOT_FOUND, + BotmuxDispatchState.UNKNOWN, + } +) + + +def _submit_trigger_attempt( + *, + binding_path: Path, + goal_id: str, + binding: Payload, + dispatch_key: str, + endpoint: str, + dashboard_auth: str, + target: PayloadView, + options: PayloadView, + instruction: str, + existing_session_id: str, + requester: JsonRequester, + writer: AtomicJsonWriter, + now_iso: NowIsoFn, +) -> Payload: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.ATTEMPTING, + timestamp_field="attempted_at", + updates={"session_reused": bool(existing_session_id)}, + session={ + **({"session_id": existing_session_id} if existing_session_id else {}), + "active_dispatch_key": dispatch_key, + "updated_at": now_iso(), + }, + writer=writer, + now_iso=now_iso, + ) + try: + response = requester( + endpoint=endpoint, + path="/api/trigger", + method="POST", + dashboard_auth=dashboard_auth, + payload={ + "source": {"type": "webhook"}, + "target": dict(target), + "instruction": instruction, + "envelope": { + "format": "json", + "sourceName": "loopx", + "trusted": False, + }, + "options": dict(options), + }, + ) + except BotmuxTransportError: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.UNKNOWN, + timestamp_field="unknown_at", + updates={"unknown_reason": "transport_failure"}, + writer=writer, + now_iso=now_iso, + ) + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_trigger", + execute=True, + status="dispatch_unknown", + blocker="botmux_dispatch_outcome_unknown", + public_summary=( + "botmux dispatch outcome is unknown; inspect the existing receipt " + "before retrying" + ), + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + ) + except BotmuxApiError as exc: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.REJECTED, + timestamp_field="rejected_at", + updates={"http_status": exc.status}, + writer=writer, + now_iso=now_iso, + ) + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_trigger", + execute=True, + status="rejected", + blocker="botmux_api_rejected", + public_summary="botmux rejected the LoopX runtime turn", + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + ) + response_target = _as_mapping(response.get("target")) or {} + async_payload = _as_mapping(response.get("async")) or {} + session_id = str( + response_target.get("sessionId") or async_payload.get("sessionId") or "" + ).strip() + if response.get("ok") is not True or not session_id: + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.UNKNOWN, + timestamp_field="unknown_at", + updates={"unknown_reason": "invalid_provider_receipt"}, + writer=writer, + now_iso=now_iso, + ) + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_trigger", + execute=True, + status="dispatch_unknown", + blocker="botmux_dispatch_receipt_invalid", + public_summary="botmux did not return a verifiable runtime session receipt", + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + ) + _persist_dispatch_receipt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + state=BotmuxDispatchState.QUEUED, + timestamp_field="queued_at", + updates={ + "session_id": session_id, + "trigger_id": str(response.get("triggerId") or ""), + }, + session={ + "session_id": session_id, + "active_dispatch_key": dispatch_key, + "updated_at": now_iso(), + }, + writer=writer, + now_iso=now_iso, + ) + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_trigger", + execute=True, + status="queued", + public_summary="queued one LoopX turn through the botmux runtime", + external_write_performed=True, + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + details={"dispatch_state": "queued", "session_reused": bool(existing_session_id)}, + ) + + +def _trigger_botmux_runtime( + *, + registry: PayloadView, + registry_path: Path, + goal_id: str, + binding_path: Path, + instruction: str | None = None, + turn_key: str | None = None, + execute: bool = False, + requester: JsonRequester, + writer: AtomicJsonWriter, + now_iso: NowIsoFn = _now_iso, +) -> Payload: + payload = read_botmux_runtime_binding(binding_path) + binding = botmux_binding_for_goal(payload, goal_id) + if binding is None or binding.get("enabled") is not True: + return _operation_packet( + ok=False, + goal_id=goal_id, + operation="runtime_trigger", + execute=execute, + status="blocked", + blocker="botmux_binding_missing", + public_summary="configure a botmux runtime binding for this goal", + ) + selected_instruction = str( + instruction or build_botmux_loopx_instruction(goal_id) + ).strip() + if not selected_instruction: + raise ValueError("botmux runtime instruction must not be empty") + revision = str( + turn_key + or goal_runtime_revision( + registry=registry, + registry_path=registry_path, + goal_id=goal_id, + ) + ) + dispatch_key = _dispatch_key( + goal_id=goal_id, + revision=revision, + instruction=selected_instruction, + ) + receipts = _as_mutable_dict(binding.get("receipts")) + prior = _as_mapping(receipts.get(dispatch_key)) + prior_state = _dispatch_state(prior.get("state") if prior is not None else None) + if prior_state in _ALREADY_DISPATCHED_STATES: + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_trigger", + execute=execute, + status="already_dispatched", + public_summary="the same botmux runtime turn was already dispatched", + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + details={ + "dispatch_state": prior_state.value, + "session_reused": True, + }, + ) + session = _as_mutable_dict(binding.get("session")) + existing_session_id = str(session.get("session_id") or "").strip() + if not execute: + return _operation_packet( + ok=True, + goal_id=goal_id, + operation="runtime_trigger", + execute=False, + status="preview_ready", + public_summary="the next LoopX turn is ready for botmux dispatch", + idempotency_key=dispatch_key, + receipt_id=_receipt_id(dispatch_key), + details={ + "dispatch_state": "preview", + "session_reused": bool(existing_session_id), + }, + ) + endpoint = _validated_endpoint(str(binding.get("endpoint") or "")) + bot_id = _validated_private_id(str(binding.get("bot_id") or ""), "bot id") + dashboard_auth = _dashboard_auth_for_binding(binding) + target: Payload = {"kind": "turn", "botId": bot_id} + options: Payload = {"asyncReturnSessionId": True} + if existing_session_id: + target["sessionId"] = _validated_private_id(existing_session_id, "session id") + options["turnIdempotencyKey"] = _provider_turn_key(dispatch_key) + else: + target["chatId"] = _validated_private_id( + str(binding.get("chat_id") or ""), + "chat id", + ) + return _submit_trigger_attempt( + binding_path=binding_path, + goal_id=goal_id, + binding=binding, + dispatch_key=dispatch_key, + endpoint=endpoint, + dashboard_auth=dashboard_auth, + target=target, + options=options, + instruction=selected_instruction, + existing_session_id=existing_session_id, + requester=requester, + writer=writer, + now_iso=now_iso, + ) diff --git a/tests/control_plane/test_botmux_runtime_contract.py b/tests/control_plane/test_botmux_runtime_contract.py new file mode 100644 index 0000000000..3e5b60a28e --- /dev/null +++ b/tests/control_plane/test_botmux_runtime_contract.py @@ -0,0 +1,141 @@ +"""Modularization, Zero-Any, and compatibility facade contracts for botmux runtime.""" + +from __future__ import annotations + +import ast +import json +from http.client import HTTPMessage +import io +from pathlib import Path +from urllib.request import Request + +import pytest + +from loopx.control_plane.goals import botmux_runtime +from loopx.control_plane.goals.botmux_transport import _decode_json_object + +REPO_ROOT = Path(__file__).resolve().parents[2] +BOTMUX_MODULES = ( + "loopx/control_plane/goals/botmux_binding_store.py", + "loopx/control_plane/goals/botmux_transport.py", + "loopx/control_plane/goals/botmux_lifecycle.py", + "loopx/control_plane/goals/botmux_trigger.py", + "loopx/control_plane/goals/botmux_status.py", + "loopx/control_plane/goals/botmux_runtime.py", + "loopx/cli_commands/goal_channel_runtime.py", +) +MODULE_LINE_BUDGET = 750 + + +def test_botmux_modules_stay_modular_and_zero_any() -> None: + for rel_path in BOTMUX_MODULES: + source = (REPO_ROOT / rel_path).read_text(encoding="utf-8") + lines = source.splitlines() + assert len(lines) < MODULE_LINE_BUDGET, f"{rel_path} has {len(lines)} lines" + assert ("type:" + " ignore") not in source, f"{rel_path} must not suppress mypy" + tree = ast.parse(source, filename=rel_path) + any_nodes = [ + node.lineno + for node in ast.walk(tree) + if isinstance(node, ast.Name) and node.id == "Any" + ] + assert any_nodes == [], f"{rel_path} uses Any at lines {any_nodes}" + + +def test_botmux_runtime_facade_preserves_monkeypatch_seams_and_exports( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + registry_path = tmp_path / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True) + state_path = tmp_path / "STATE.md" + state_path.write_text("# State\n", encoding="utf-8") + registry = { + "goals": [ + { + "id": "goal-fixture", + "repo": str(tmp_path), + "state_file": str(state_path), + } + ] + } + registry_path.write_text(json.dumps(registry), encoding="utf-8") + binding_path = tmp_path / ".loopx" / "goal-channel-runtime.json" + monkeypatch.setenv("BOTMUX_TEST_TOKEN", "fixture-token") + + requested_paths: list[str] = [] + + def fake_request_json(**kwargs: object) -> dict[str, object]: + path = str(kwargs["path"]) + requested_paths.append(path) + if path == "/__health": + return {"ok": True} + if path == "/api/bots": + return { + "bots": [ + { + "larkAppId": "bot-fixture", + "online": True, + "defaultWorkingDir": str(tmp_path.resolve()), + } + ] + } + if path == "/api/groups": + return { + "chats": [ + { + "chatId": "chat-fixture", + "memberBots": [ + {"larkAppId": "bot-fixture", "inChat": True, "oncallChat": None} + ], + } + ] + } + if path == "/api/trigger": + return {"ok": True, "action": "dry_run"} + raise AssertionError(f"unexpected path: {path}") + + fixed_iso = "2026-11-26T00:00:00+00:00" + monkeypatch.setattr(botmux_runtime, "_request_json", fake_request_json) + monkeypatch.setattr(botmux_runtime, "_now_iso", lambda: fixed_iso) + + result = botmux_runtime.setup_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + endpoint="http://127.0.0.1:7891", + bot_id="bot-fixture", + chat_id="chat-fixture", + token_env="BOTMUX_TEST_TOKEN", + execute=True, + ) + + assert result["status"] == "configured" + assert "/__health" in requested_paths + persisted = botmux_runtime.botmux_binding_for_goal( + botmux_runtime.read_botmux_runtime_binding(binding_path), + "goal-fixture", + ) + assert persisted is not None + assert persisted["verified_at"] == fixed_iso + for symbol in botmux_runtime.__all__: + assert hasattr(botmux_runtime, symbol) + + +def test_botmux_transport_rejects_redirects_and_non_dict_json() -> None: + handler = botmux_runtime._NoRedirectHandler() + redirected = handler.redirect_request( + Request("http://127.0.0.1:7891/__health"), + io.BytesIO(b""), + 302, + "Found", + HTTPMessage(), + "https://example.invalid/redirect", + ) + assert redirected is None + + with pytest.raises(botmux_runtime.BotmuxTransportError, match="non-JSON"): + _decode_json_object(b"not-json") + with pytest.raises(botmux_runtime.BotmuxTransportError, match="invalid JSON"): + _decode_json_object(b'["array"]') From d200454ef778499f15b69fcbabc2cb8eeccd6954 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:38:27 +0800 Subject: [PATCH 2/2] fix(botmux): preserve KV binding sections and fail closed on corrupt receipts or session Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../goals/botmux_binding_store.py | 36 ++- loopx/control_plane/goals/botmux_lifecycle.py | 16 +- loopx/control_plane/goals/botmux_status.py | 18 +- loopx/control_plane/goals/botmux_trigger.py | 6 +- .../test_botmux_runtime_contract.py | 273 +++++++++++++++++- 5 files changed, 323 insertions(+), 26 deletions(-) diff --git a/loopx/control_plane/goals/botmux_binding_store.py b/loopx/control_plane/goals/botmux_binding_store.py index 6a5121d1d2..486faf1da6 100644 --- a/loopx/control_plane/goals/botmux_binding_store.py +++ b/loopx/control_plane/goals/botmux_binding_store.py @@ -137,11 +137,31 @@ def _as_mapping(value: object) -> PayloadView | None: return None -def _as_mutable_dict(value: object) -> Payload: - mapping = _as_mapping(value) - if mapping is None: +def _coerce_binding_section(value: object, *, field: str) -> Payload: + """Coerce missing, mapping, or KV-pair sequence sections; reject corrupt shapes.""" + if value is None: return {} - return {str(key): item for key, item in mapping.items()} + if isinstance(value, Mapping): + mapping = cast(Mapping[object, object], value) + normalized: Payload = {} + for key, item in mapping.items(): + if not isinstance(key, str): + raise ValueError(f"botmux runtime {field} must use string keys") + normalized[key] = item + return normalized + if isinstance(value, (list, tuple)): + entries = cast(list[object] | tuple[object, ...], value) + recovered: Payload = {} + for entry in entries: + if not isinstance(entry, (list, tuple)) or len(entry) != 2: + raise ValueError(f"botmux runtime {field} must be a mapping") + pair = cast(list[object] | tuple[object, ...], entry) + key = pair[0] + if not isinstance(key, str): + raise ValueError(f"botmux runtime {field} must use string keys") + recovered[key] = pair[1] + return recovered + raise ValueError(f"botmux runtime {field} must be a mapping") def _as_string_dict(value: object) -> Payload | None: @@ -264,7 +284,9 @@ def _persist_dispatch_receipt( current_binding = botmux_binding_for_goal(payload, goal_id) if current_binding is None: raise ValueError("botmux runtime binding disappeared during dispatch") - receipts = _as_mutable_dict(current_binding.get("receipts")) + receipts = _coerce_binding_section( + current_binding.get("receipts"), field="receipts" + ) receipt = _transition_dispatch_receipt( _as_mapping(receipts.get(dispatch_key)), state=state, @@ -291,8 +313,8 @@ def _persist_dispatch_receipt( def _active_dispatch_receipt( binding: PayloadView, ) -> tuple[str, Payload] | None: - receipts = _as_mapping(binding.get("receipts")) or {} - session = _as_mapping(binding.get("session")) or {} + receipts = _coerce_binding_section(binding.get("receipts"), field="receipts") + session = _coerce_binding_section(binding.get("session"), field="session") active_key = str(session.get("active_dispatch_key") or "").strip() active = _as_mapping(receipts.get(active_key)) if active_key else None if active_key and active is not None: diff --git a/loopx/control_plane/goals/botmux_lifecycle.py b/loopx/control_plane/goals/botmux_lifecycle.py index 0b675f30c9..3ee488d928 100644 --- a/loopx/control_plane/goals/botmux_lifecycle.py +++ b/loopx/control_plane/goals/botmux_lifecycle.py @@ -20,7 +20,7 @@ NowIsoFn, Payload, PayloadView, - _as_mapping, + _coerce_binding_section, _now_iso, _operation_packet, _save_binding, @@ -111,8 +111,6 @@ def _setup_botmux_runtime( and prior.get("token_env") == token_env and prior.get("expected_working_dir") == str(expected_working_dir) ) - prior_session = _as_mapping(prior.get("session")) - prior_receipts = _as_mapping(prior.get("receipts")) binding: Payload = { "goal_id": goal_id, "provider": BOTMUX_PROVIDER, @@ -122,8 +120,16 @@ def _setup_botmux_runtime( "chat_id": chat_id, "token_env": token_env, "expected_working_dir": str(expected_working_dir), - "session": dict(prior_session) if same_route and prior_session else {}, - "receipts": dict(prior_receipts) if same_route and prior_receipts else {}, + "session": ( + _coerce_binding_section(prior.get("session"), field="session") + if same_route + else {} + ), + "receipts": ( + _coerce_binding_section(prior.get("receipts"), field="receipts") + if same_route + else {} + ), } try: probe = _probe_botmux(binding=binding, requester=requester) diff --git a/loopx/control_plane/goals/botmux_status.py b/loopx/control_plane/goals/botmux_status.py index c701f82dec..29ef46e0ce 100644 --- a/loopx/control_plane/goals/botmux_status.py +++ b/loopx/control_plane/goals/botmux_status.py @@ -17,7 +17,7 @@ PayloadView, _active_dispatch_receipt, _as_mapping, - _as_mutable_dict, + _coerce_binding_section, _dispatch_state, _now_iso, _operation_packet, @@ -123,7 +123,7 @@ def _record_status_transport_failure( now_iso: NowIsoFn, ) -> Payload: if execute: - receipts = _as_mapping(binding.get("receipts")) or {} + receipts = _coerce_binding_section(binding.get("receipts"), field="receipts") receipt = _as_mapping(receipts.get(dispatch_key)) current_state = _dispatch_state( receipt.get("state") if receipt is not None else None @@ -275,15 +275,11 @@ def _status_botmux_runtime( blocker="botmux_binding_missing", public_summary="configure a botmux runtime binding for this goal", ) - session = _as_mutable_dict(binding.get("session")) + session = _coerce_binding_section(binding.get("session"), field="session") session_id = str(session.get("session_id") or "").strip() dispatch_key = str(session.get("active_dispatch_key") or "").strip() - local_receipts = _as_mapping(binding.get("receipts")) - local_receipt = ( - _as_mapping(local_receipts.get(dispatch_key)) - if (local_receipts is not None and dispatch_key) - else None - ) + local_receipts = _coerce_binding_section(binding.get("receipts"), field="receipts") + local_receipt = _as_mapping(local_receipts.get(dispatch_key)) if dispatch_key else None local_state = _dispatch_state( local_receipt.get("state") if local_receipt is not None else None ) @@ -348,7 +344,9 @@ def _status_botmux_runtime( identity_unverified = True latest_payload = read_botmux_runtime_binding(binding_path) latest_binding = botmux_binding_for_goal(latest_payload, goal_id) or binding - latest_receipts = _as_mapping(latest_binding.get("receipts")) or {} + latest_receipts = _coerce_binding_section( + latest_binding.get("receipts"), field="receipts" + ) latest_receipt = _as_mapping(latest_receipts.get(dispatch_key)) latest_local_state = _dispatch_state( latest_receipt.get("state") if latest_receipt is not None else None diff --git a/loopx/control_plane/goals/botmux_trigger.py b/loopx/control_plane/goals/botmux_trigger.py index 47f786576f..3c39faba0c 100644 --- a/loopx/control_plane/goals/botmux_trigger.py +++ b/loopx/control_plane/goals/botmux_trigger.py @@ -14,7 +14,7 @@ Payload, PayloadView, _as_mapping, - _as_mutable_dict, + _coerce_binding_section, _dispatch_state, _now_iso, _operation_packet, @@ -251,9 +251,10 @@ def _trigger_botmux_runtime( revision=revision, instruction=selected_instruction, ) - receipts = _as_mutable_dict(binding.get("receipts")) + receipts = _coerce_binding_section(binding.get("receipts"), field="receipts") prior = _as_mapping(receipts.get(dispatch_key)) prior_state = _dispatch_state(prior.get("state") if prior is not None else None) + session = _coerce_binding_section(binding.get("session"), field="session") if prior_state in _ALREADY_DISPATCHED_STATES: return _operation_packet( ok=True, @@ -269,7 +270,6 @@ def _trigger_botmux_runtime( "session_reused": True, }, ) - session = _as_mutable_dict(binding.get("session")) existing_session_id = str(session.get("session_id") or "").strip() if not execute: return _operation_packet( diff --git a/tests/control_plane/test_botmux_runtime_contract.py b/tests/control_plane/test_botmux_runtime_contract.py index 3e5b60a28e..763db6689c 100644 --- a/tests/control_plane/test_botmux_runtime_contract.py +++ b/tests/control_plane/test_botmux_runtime_contract.py @@ -2,15 +2,19 @@ from __future__ import annotations +import argparse import ast +from collections.abc import Mapping +import io import json from http.client import HTTPMessage -import io from pathlib import Path +from typing import cast from urllib.request import Request import pytest +from loopx.cli_commands import goal_channel_runtime from loopx.control_plane.goals import botmux_runtime from loopx.control_plane.goals.botmux_transport import _decode_json_object @@ -139,3 +143,270 @@ def test_botmux_transport_rejects_redirects_and_non_dict_json() -> None: _decode_json_object(b"not-json") with pytest.raises(botmux_runtime.BotmuxTransportError, match="invalid JSON"): _decode_json_object(b'["array"]') + + +def _setup_fixture_binding( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> tuple[dict[str, object], Path, Path, list[dict[str, object]]]: + registry_path = tmp_path / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True, exist_ok=True) + state_path = tmp_path / "STATE.md" + state_path.write_text("# State\n", encoding="utf-8") + registry: dict[str, object] = { + "goals": [ + { + "id": "goal-fixture", + "repo": str(tmp_path), + "state_file": str(state_path), + } + ] + } + registry_path.write_text(json.dumps(registry), encoding="utf-8") + binding_path = tmp_path / ".loopx" / "goal-channel-runtime.json" + monkeypatch.setenv("BOTMUX_TEST_TOKEN", "fixture-token") + calls: list[dict[str, object]] = [] + + def requester(**kwargs: object) -> dict[str, object]: + calls.append(dict(kwargs)) + path = str(kwargs["path"]) + if path == "/__health": + return {"ok": True} + if path == "/api/bots": + return { + "bots": [ + { + "larkAppId": "bot-fixture", + "online": True, + "defaultWorkingDir": str(tmp_path.resolve()), + } + ] + } + if path == "/api/groups": + return { + "chats": [ + { + "chatId": "chat-fixture", + "memberBots": [ + { + "larkAppId": "bot-fixture", + "inChat": True, + "oncallChat": None, + } + ], + } + ] + } + if path == "/api/trigger": + body = cast(Mapping[str, object], kwargs["payload"]) + options = cast(Mapping[str, object], body["options"]) + if options.get("dryRun") is True: + return {"ok": True, "action": "dry_run"} + return { + "ok": True, + "action": "queued", + "triggerId": "trigger-fixture", + "target": {"sessionId": "session-fixture"}, + } + if "/trigger-result" in path: + return { + "ok": True, + "state": "completed", + "triggerId": "trigger-fixture", + "output": {"content": "done"}, + } + raise AssertionError(f"unexpected path: {path}") + + monkeypatch.setattr(botmux_runtime, "_request_json", requester) + setup_res = botmux_runtime.setup_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + endpoint="http://127.0.0.1:7891", + bot_id="bot-fixture", + chat_id="chat-fixture", + token_env="BOTMUX_TEST_TOKEN", + execute=True, + ) + assert setup_res["status"] == "configured" + calls.clear() + return registry, registry_path, binding_path, calls + + +def test_botmux_binding_handles_missing_and_recoverable_sections( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + registry, registry_path, binding_path, calls = _setup_fixture_binding( + tmp_path, monkeypatch + ) + + payload = botmux_runtime.read_botmux_runtime_binding(binding_path) + bindings = cast(dict[str, object], payload["bindings"]) + binding = cast(dict[str, object], bindings["goal-fixture"]) + binding["receipts"] = None + binding["session"] = None + binding_path.write_text(json.dumps(payload), encoding="utf-8") + + queued = botmux_runtime.trigger_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + turn_key="turn-1", + execute=True, + ) + assert queued["status"] == "queued" + assert len(calls) == 1 + first_target = cast( + Mapping[str, object], cast(Mapping[str, object], calls[0]["payload"])["target"] + ) + assert first_target.get("chatId") == "chat-fixture" + calls.clear() + + completed = botmux_runtime.status_botmux_runtime( + goal_id="goal-fixture", + binding_path=binding_path, + execute=True, + ) + assert completed["status"] == "completed" + calls.clear() + + payload = botmux_runtime.read_botmux_runtime_binding(binding_path) + bindings = cast(dict[str, object], payload["bindings"]) + binding = cast(dict[str, object], bindings["goal-fixture"]) + stored_receipts = cast(dict[str, object], binding["receipts"]) + stored_session = cast(dict[str, object], binding["session"]) + dispatch_key = str(stored_session["active_dispatch_key"]) + binding["receipts"] = [[dispatch_key, stored_receipts[dispatch_key]]] + binding["session"] = [ + ["session_id", stored_session["session_id"]], + ["active_dispatch_key", dispatch_key], + ] + binding_path.write_text(json.dumps(payload), encoding="utf-8") + kv_bytes = binding_path.read_bytes() + + duplicate = botmux_runtime.trigger_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + turn_key="turn-1", + execute=True, + ) + assert duplicate["status"] == "already_dispatched" + assert calls == [] + assert binding_path.read_bytes() == kv_bytes + + status_kv = botmux_runtime.status_botmux_runtime( + goal_id="goal-fixture", + binding_path=binding_path, + execute=False, + ) + assert status_kv["status"] == "completed" + calls.clear() + + followup = botmux_runtime.trigger_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + turn_key="turn-2", + execute=True, + ) + assert followup["status"] == "queued" + assert len(calls) == 1 + reused_payload = cast(Mapping[str, object], calls[0]["payload"]) + assert cast(Mapping[str, object], reused_payload["target"]).get("sessionId") == ( + "session-fixture" + ) + assert "turnIdempotencyKey" in cast(Mapping[str, object], reused_payload["options"]) + + +@pytest.mark.parametrize("field", ["receipts", "session"]) +@pytest.mark.parametrize( + "corrupt_value", + ["corrupted-section", ["bad-item"], ["ab"], 123, True, [[123, {}]]], +) +def test_botmux_rejects_corrupt_sections_before_provider_post_or_write( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + field: str, + corrupt_value: object, +) -> None: + registry, registry_path, binding_path, calls = _setup_fixture_binding( + tmp_path, monkeypatch + ) + first = botmux_runtime.trigger_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + turn_key="turn-1", + execute=True, + ) + assert first["status"] == "queued" + calls.clear() + + payload = botmux_runtime.read_botmux_runtime_binding(binding_path) + bindings = cast(dict[str, object], payload["bindings"]) + binding = cast(dict[str, object], bindings["goal-fixture"]) + binding[field] = corrupt_value + binding_path.write_text(json.dumps(payload), encoding="utf-8") + preserved = binding_path.read_bytes() + + with pytest.raises(ValueError, match=field): + botmux_runtime.trigger_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + turn_key="turn-2", + execute=True, + ) + assert calls == [] + assert binding_path.read_bytes() == preserved + + with pytest.raises(ValueError, match=field): + botmux_runtime.status_botmux_runtime( + goal_id="goal-fixture", + binding_path=binding_path, + execute=True, + ) + assert calls == [] + assert binding_path.read_bytes() == preserved + + with pytest.raises(ValueError, match=field): + botmux_runtime.setup_botmux_runtime( + registry=registry, + registry_path=registry_path, + goal_id="goal-fixture", + binding_path=binding_path, + endpoint="http://127.0.0.1:7891", + bot_id="bot-fixture", + chat_id="chat-fixture", + token_env="BOTMUX_TEST_TOKEN", + execute=True, + ) + assert calls == [] + assert binding_path.read_bytes() == preserved + + cli_trigger = goal_channel_runtime.run_goal_channel_runtime( + argparse.Namespace( + goal_id="goal-fixture", + runtime_binding_path=str(binding_path), + goal_channel_runtime_command="trigger", + instruction=None, + turn_key="turn-2", + execute=True, + ), + registry=registry, + registry_path=registry_path, + ) + assert cli_trigger["ok"] is False + assert cli_trigger["status"] == "blocked" + assert cli_trigger["blocker"] == "invalid_configuration" + assert cli_trigger["external_write_performed"] is False + assert calls == [] + assert binding_path.read_bytes() == preserved