diff --git a/loopx/capabilities/native_chat/conversation_binding_agents.py b/loopx/capabilities/native_chat/conversation_binding_agents.py new file mode 100644 index 0000000000..ba7e213416 --- /dev/null +++ b/loopx/capabilities/native_chat/conversation_binding_agents.py @@ -0,0 +1,538 @@ +"""Steward executor reconciliation, binding stop/recovery, and attached-agent checks.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +import logging +from pathlib import Path + +from ...chat_store import TERMINAL_TURN_STATES +from ...file_lock import exclusive_file_lock +from .conversation_binding_contracts import ( + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingSessionStoreProtocol, + BindingStateDict, + CoreEffectFn, + LockFn, + ObserveFn, + ProjectContextsProtocol, + ReadJsonFn, + WriteJsonFn, + as_binding_payload, + host_audiences, + host_ref, + session_observation, +) + + +def reconcile_steward_executors_flow( + *, + controller: BindingControllerProtocol | None, + read_fn: Callable[[], BindingStateDict], + reconcile_one_fn: Callable[[BindingPayload, BindingPayloadView], None], +) -> None: + """Publish a previously adopted machine executor across eligible steward bindings.""" + from ...chat_manager import steward_machine_defaults + + if controller is None: + return + defaults = steward_machine_defaults(controller) + if ( + not defaults + or defaults.get("status") != "ready" + or defaults.get("source") != "machine_configuration" + or defaults.get("selection_policy") not in {"preferred", "pinned"} + or defaults.get("executor_endpoint") not in {"antigravity", "codex"} + ): + return + try: + rows = read_fn()["bindings"] + if not isinstance(rows, list): + raise ValueError("invalid conversation bindings state") + except (OSError, ValueError, KeyError) as exc: + logging.getLogger(__name__).warning( + "Steward bindings unavailable for reconciliation (%s)", + type(exc).__name__, + ) + return + for row in rows: + if ( + not isinstance(row, dict) + or row.get("context_kind") != "steward" + or row.get("audience", "owner") != "owner" + or row.get("enabled") is not True + or row.get("executor_endpoint_id") not in {"antigravity", "codex"} + or row.get("executor_endpoint_id") == defaults["executor_endpoint"] + ): + continue + try: + reconcile_one_fn(row, defaults) + except (OSError, ValueError, TypeError, KeyError, RuntimeError) as exc: + logging.getLogger(__name__).warning( + "Steward executor reconciliation held (%s)", + type(exc).__name__, + ) + + +def reconcile_steward_executor_flow( + *, + bindings_path: Path, + controller: BindingControllerProtocol, + projects: ProjectContextsProtocol, + row: BindingPayloadView, + defaults: BindingPayloadView, + read_fn: Callable[[], BindingStateDict], + observe_fn: ObserveFn, + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + goal_scope_ids_fn: Callable[[BindingPayloadView], list[str]], + lock_fn: LockFn = exclusive_file_lock, +) -> None: + """Reconcile one eligible owner steward binding with adopted machine defaults.""" + from ...chat_manager import manager_executor_allocation, steward_machine_defaults + from ..machine_configuration.builtins import ( + build_builtin_machine_configuration_registry, + ) + from ..machine_configuration.contract import machine_configuration_revision + from ..machine_configuration.store import read_machine_configuration + from ..steward_executor.allocation import normalize_manager_executor_allocation + from ..steward_executor.machine_defaults import effective_steward_executor_defaults + + store = controller.store + binding_id = str(row["binding_id"]) + endpoint = str(defaults["executor_endpoint"]) + channel_prefix = f"manager.external.native.{binding_id}." + all_open = [ + session + for session in store.list_sessions() + if str(session.get("channel_id") or "").startswith(channel_prefix) + and session.get("status") != "closed" + ] + candidates: list[BindingPayload] = [] + for candidate in all_open: + steward_context = candidate.get("steward_context") + if not (isinstance(steward_context, Mapping) and steward_context.get("topic_ref")): + candidates.append(candidate) + if ( + len(candidates) != 1 + or candidates[0].get("agent_id") != endpoint + or candidates[0].get("status") != "ready" + or any( + open_session.get("status") != "ready" + or open_session.get("active_turn_id") is not None + for open_session in all_open + ) + ): + return # Defaults alone do not retarget an existing session. + observation = observe_fn(str(row["transport_ref"])) + candidate_session_id = str(candidates[0]["session_id"]) + with lock_fn(bindings_path, operation="reconcile_steward_executor"): + current = read_fn() + if row not in current["bindings"] or steward_machine_defaults(controller) != defaults: + return + session = store.load_session(candidate_session_id) + saved = session.get("steward_context") if session is not None else None + stored = session.get("manager_executor_allocation") if session is not None else None + if ( + not session + or not isinstance(saved, dict) + or not isinstance(stored, dict) + or session.get("status") != "ready" + or session.get("active_turn_id") is not None + or session.get("agent_id") != endpoint + or session.get("executor_endpoint_id") != endpoint + or stored.get("selection_policy") != defaults["selection_policy"] + or store.queued_turns(str(session["session_id"]), strict=True, include_reserved=True) + ): + return + allocation: BindingPayload | None = None + if stored.get("configuration_revision") == defaults.get("configuration_revision"): + try: + allocation = as_binding_payload(normalize_manager_executor_allocation(stored)) + except (TypeError, ValueError): + pass + else: + # A machine configuration transaction records the revision of + # the whole document. Match that exact basis before projecting + # it to the narrower revision used by steward allocations. + configuration = read_machine_configuration( + store.root.parent, + registry=build_builtin_machine_configuration_registry(), + ) + if ( + not configuration + or machine_configuration_revision(configuration) + != stored.get("configuration_revision") + or effective_steward_executor_defaults(configuration) != defaults + ): + return + if allocation is None: + allocation = as_binding_payload( + manager_executor_allocation(controller, machine_defaults=dict(defaults)) + ) + expected = { + **session_observation(session), + "manager_executor_allocation": allocation, + "active_turn_id": session.get("active_turn_id"), + "agent_model_id": session.get("agent_model_id"), + "agent_reasoning_effort": session.get("agent_reasoning_effort"), + } + result = core_fn( + "collaboration.conversation.binding", + { + "current": current, + "expected_revision": current["revision"], + "operation": "reconcile_steward_executor", + "binding_id": binding_id, + "observation": observation, + "available_projects": projects.available(), + "available_goal_ids": goal_scope_ids_fn(row), + "machine_defaults": dict(defaults), + "session": expected, + "queue_empty": True, + }, + ) + upstream_thread_id = session.get("upstream_thread_id") + if stored != allocation: + store.update_session( + str(session["session_id"]), + expected_statuses={"ready"}, + expected_upstream_thread_id=( + upstream_thread_id if isinstance(upstream_thread_id, str) else None + ), + manager_executor_allocation=allocation, + ) + fresh = store.load_session(str(session["session_id"])) + if ( + not fresh + or any(fresh.get(key) != value for key, value in expected.items()) + or store.queued_turns(str(session["session_id"]), strict=True, include_reserved=True) + or steward_machine_defaults(controller) != defaults + ): + return + if result["changed"]: + write_json_fn(bindings_path, result["state"], preserve_mode=True) + if read_fn() != result["state"]: + raise OSError("steward executor binding publication did not verify") + + +def stop_revoked_binding_flow( + controller: BindingControllerProtocol | None, + binding_id: str, +) -> None: + """Apply the committed grant decision through existing exact Turn control.""" + if controller is None: + return + store = controller.store + failures: list[Exception] = [] + for row in store.list_sessions(): + session = store.load_session(str(row["session_id"])) + if session is None: + continue + bound = any( + isinstance(ctx := session.get(key), dict) + and ctx.get("binding_id") == binding_id + for key in ("project_context", "steward_context") + ) + turns = list(store.queued_turns(str(session["session_id"]))) + active_turn_id = session.get("active_turn_id") + active = ( + store.load_turn(str(session["session_id"]), str(active_turn_id)) + if active_turn_id + else None + ) + if active: + turns.append(active) + for turn in turns: + raw_target = turn.get("external_agent_target") + target_context = ( + raw_target.get("context") + if isinstance(raw_target, Mapping) + else None + ) + target_binding = ( + target_context.get("binding_id") + if isinstance(target_context, Mapping) + else None + ) + if ( + (not bound and target_binding != binding_id) + or turn.get("status") in TERMINAL_TURN_STATES + ): + continue + try: + stopped = controller.interrupt_turn( + session_id=str(session["session_id"]), + turn_id=str(turn["turn_id"]), + ) + if stopped.get("status") not in TERMINAL_TURN_STATES: + raise RuntimeError("Turn stop did not settle") + except Exception as exc: + # Revocation remains published even when a host lacks stop + # control. Continue stopping other exact targets, then report + # failure without exposing private transport diagnostics. + failures.append(exc) + if failures: + raise OSError( + "Conversation grant revoked; execution stop is not confirmed. " + "Retry stop for this binding." + ) from failures[0] + + +def stop_recoveries_flow( + controller: BindingControllerProtocol | None, + current: BindingPayloadView, +) -> list[BindingPayload]: + """Project revoked execution counts per binding from canonical Turns.""" + if controller is None: + return [] + raw_bindings = current["bindings"] + if not isinstance(raw_bindings, list): + return [] + authorized = { + row["binding_id"] + for row in raw_bindings + if isinstance(row, Mapping) and "binding_id" in row + } + store = controller.store + pending: dict[str, tuple[str, int]] = {} + for row in store.list_sessions(): + session = store.load_session(str(row["session_id"])) + if session is None: + continue + turns = list(store.queued_turns(str(session["session_id"]))) + active_turn_id = session.get("active_turn_id") + active = ( + store.load_turn(str(session["session_id"]), str(active_turn_id)) + if active_turn_id + else None + ) + if active: + turns.append(active) + for turn in turns: + if turn.get("status") in TERMINAL_TURN_STATES: + continue + raw_target = turn.get("external_agent_target") + target_ctx = ( + raw_target.get("context") + if isinstance(raw_target, Mapping) + else None + ) + context = ( + target_ctx + or session.get("project_context") + or session.get("steward_context") + or {} + ) + if not isinstance(context, Mapping): + continue + binding_id = context.get("binding_id") + if not isinstance(binding_id, str) or not binding_id or binding_id in authorized: + continue + project_ref = str(context.get("project_ref") or "") + existing_ref, count = pending.get(binding_id, (project_ref, 0)) + pending[binding_id] = (existing_ref, count + 1) + return [ + { + "binding_id": key, + "project_ref": pending[key][0], + "pending_count": pending[key][1], + } + for key in sorted(pending) + ] + + +def agent_observation_flow( + controller: BindingControllerProtocol | None, + session_id: str, +) -> BindingPayload: + """Read only the explicitly selected canonical attached Session/Goal.""" + from ...attached_session import _require_bound_host, require_current_attached_session + from ...control_plane.projects.registry_codec import load_registry + from ...registry import find_registry_goal + + if controller is None or controller.registry_path is None: + raise ValueError("the attached Session registry is unavailable") + session = require_current_attached_session( + store=controller.store, + registry_path=controller.registry_path, + session_id=session_id, + ) + registry = load_registry(controller.registry_path) + goal = find_registry_goal(registry, str(session.get("goal_id") or "")) + if goal is None or not goal.get("repo"): + raise ValueError("the exact Agent workspace is unavailable") + _require_bound_host( + goal=goal, + agent_id=str(session["agent_id"]), + host_surface=str(session["host_surface"]), + host_session_id=str(session["upstream_thread_id"]), + ) + raw_coordination = goal.get("coordination") + registered_agents = ( + raw_coordination.get("registered_agents", []) + if isinstance(raw_coordination, Mapping) + else [] + ) + return { + "session": { + key: session.get(key) + for key in [ + "session_id", + "goal_id", + "goal_instance_id", + "agent_id", + "executor_endpoint_id", + "session_mode", + "status", + "external_conversation_binding_id", + ] + }, + "goal": { + "goal_id": goal["id"], + "workspace_path": str(Path(str(goal["repo"])).resolve()), + "registered_agents": registered_agents, + }, + "host_binding_verified": True, + "host_ref": host_ref(session), + "host_audience_binding_ids": host_audiences(controller.store, session), + } + + +def agent_candidates_flow( + *, + binding_id: str, + controller: BindingControllerProtocol | None, + projects: ProjectContextsProtocol | None, + read_fn: Callable[[], BindingStateDict], + observe_agent_fn: Callable[[str], BindingPayload], +) -> list[BindingPayload]: + """Return attached host sessions eligible for external delegation under a binding.""" + row = next( + item for item in read_fn()["bindings"] if item["binding_id"] == binding_id + ) + if ( + row["context_kind"] != "project" + or row.get("audience") == "group" + or controller is None + or projects is None + ): + if ( + row["context_kind"] != "project" + or row.get("audience") == "group" + or controller is None + ): + return [] + raise ValueError("bound conversation project contexts are unavailable") + project = next( + ( + item + for item in projects.available() + if item["project_ref"] == row["project_ref"] + ), + None, + ) + if project is None: + return [] + candidates: list[BindingPayload] = [] + for session in controller.store.list_sessions(): + if ( + session.get("session_mode") != "attached_host" + or session.get("status") == "closed" + ): + continue + try: + observed = observe_agent_fn(str(session["session_id"])) + observed_session = observed["session"] + observed_goal = observed["goal"] + audience_ids = observed["host_audience_binding_ids"] + if ( + isinstance(observed_session, dict) + and isinstance(observed_goal, Mapping) + and isinstance(audience_ids, list) + and observed_session["status"] in {"ready", "busy"} + and observed_goal["workspace_path"] == project["workspace_path"] + and observed_session.get("external_conversation_binding_id") + in {None, binding_id} + and all(owner == binding_id for owner in audience_ids) + ): + candidates.append(observed_session) + except (ValueError, OSError, KeyError): + continue + return candidates[:16] + + +def validate_external_agent_turn_flow( + *, + store: BindingSessionStoreProtocol, + session: BindingPayloadView, + goal: BindingPayloadView | None, + turn: BindingPayloadView, + read_json_fn: ReadJsonFn, + core_fn: CoreEffectFn, +) -> None: + """Verify external attached-agent audience grant and host binding under fences.""" + saved = turn.get("external_agent_target") + if saved is None: + return + from ...attached_session import _require_bound_host + + if ( + not isinstance(saved, dict) + or turn.get("origin") not in {"lark", "external"} + or goal is None + ): + raise ValueError("the attached external audience is unavailable") + context = saved["context"] + target = saved["target"] + if not Path(str(goal["repo"])).is_dir(): + raise ValueError("the attached Agent workspace is unavailable") + state = read_json_fn(store.root / "conversation-bindings.json") + raw_bindings = state["bindings"] + selected = ( + next( + ( + row + for row in raw_bindings + if isinstance(row, Mapping) + and row["binding_id"] == context["binding_id"] + ), + None, + ) + if isinstance(raw_bindings, list) + else None + ) + if selected is None: + raise ValueError("the Agent audience grant was revoked") + _require_bound_host( + goal=dict(goal), + agent_id=str(session["agent_id"]), + host_surface=str(session["host_surface"]), + host_session_id=str(session["upstream_thread_id"]), + ) + raw_coordination = goal.get("coordination") + registered_agents = ( + raw_coordination.get("registered_agents", []) + if isinstance(raw_coordination, Mapping) + else [] + ) + core_fn( + "collaboration.conversation.agent_target", + { + "binding": selected, + "context": context, + "target": target, + "target_observation": { + "session": session, + "goal": { + "goal_id": goal["id"], + "workspace_path": str(Path(str(goal["repo"])).resolve()), + "registered_agents": registered_agents, + }, + "host_binding_verified": True, + "host_ref": host_ref(session), + "host_audience_binding_ids": host_audiences(store, session), + }, + }, + ) diff --git a/loopx/capabilities/native_chat/conversation_binding_contracts.py b/loopx/capabilities/native_chat/conversation_binding_contracts.py new file mode 100644 index 0000000000..f0ea062b94 --- /dev/null +++ b/loopx/capabilities/native_chat/conversation_binding_contracts.py @@ -0,0 +1,427 @@ +"""Typed contracts, protocols, and shared pure helpers for conversation bindings.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager +import hashlib +from pathlib import Path +from typing import TYPE_CHECKING, Literal, Protocol, overload + +from ...control_plane.effect_runtime import EffectRuntimeRejected, effect_runtime_result + +if TYPE_CHECKING: + from ...chat_store import ChatSessionStore + +BindingPayload = dict[str, object] +BindingPayloadView = Mapping[str, object] +ObserveFn = Callable[[str], BindingPayloadView] +EventSinkFn = Callable[[str, BindingPayload], None] +CoreEffectFn = Callable[..., BindingPayload] +ReadJsonFn = Callable[[Path], BindingPayload] +WriteJsonFn = Callable[..., None] +ReplyStatusFn = Callable[[Path, BindingPayload], Sequence[BindingPayload]] +InspectResultFn = Callable[[BindingPayload, BindingPayload, Path], object] +LockFn = Callable[..., AbstractContextManager[object]] + + +class ObserveAudienceFn(Protocol): + def __call__( + self, transport_ref: str, *, audience: str | None = None + ) -> BindingPayloadView: ... + + +class BindingRowDict(dict[str, object]): + """Structured dict representing one persisted conversation binding entry.""" + + @overload + def __getitem__( + self, + key: Literal[ + "schema_version", + "binding_id", + "transport_ref", + "provider_ref", + "operator_ref", + "context_kind", + "project_ref", + "executor_endpoint_id", + "grant", + "goal_scope", + "audience", + ], + /, + ) -> str: ... + + @overload + def __getitem__(self, key: Literal["enabled"], /) -> bool: ... + + @overload + def __getitem__( + self, + key: Literal["goal_ids", "group_refs"], + /, + ) -> list[str]: ... + + @overload + def __getitem__( + self, + key: Literal["agent_targets"], + /, + ) -> list[BindingPayload]: ... + + @overload + def __getitem__( + self, + key: Literal["managed_actor"], + /, + ) -> BindingPayload | None: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +class BindingStateDict(dict[str, object]): + """Structured dict representing the persisted conversation-bindings document.""" + + @overload + def __getitem__(self, key: Literal["schema_version"], /) -> str: ... + + @overload + def __getitem__(self, key: Literal["revision"], /) -> int: ... + + @overload + def __getitem__( + self, + key: Literal["app_steward_binding_id"], + /, + ) -> str | None: ... + + @overload + def __getitem__( + self, + key: Literal["bindings"], + /, + ) -> list[BindingRowDict]: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +class ResolvedBindingDict(dict[str, object]): + """Structured dict returned when resolving a verified bound conversation.""" + + @overload + def __getitem__(self, key: Literal["binding"], /) -> BindingRowDict: ... + + @overload + def __getitem__( + self, + key: Literal["context", "observation"], + /, + ) -> BindingPayload: ... + + @overload + def __getitem__(self, key: Literal["channel_id"], /) -> str: ... + + @overload + def __getitem__(self, key: Literal["owner_manager_audience"], /) -> bool: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +class AppStewardTargetDict(dict[str, object]): + """Structured dict returned by ``app_steward_target``.""" + + @overload + def __getitem__( + self, + key: Literal["binding_id", "session_id"], + /, + ) -> str | None: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +class LocalSessionSnapshotDict(dict[str, object]): + """Structured dict returned by ``local_session_snapshot``.""" + + @overload + def __getitem__(self, key: Literal["sessions"], /) -> list[BindingPayload]: ... + + @overload + def __getitem__( + self, + key: Literal["conversation_source"], + /, + ) -> BindingPayload: ... + + @overload + def __getitem__(self, key: str, /) -> object: ... + + def __getitem__(self, key: str, /) -> object: + return super().__getitem__(key) + + +class BindingAuthorityProtocol(Protocol): + """Protocol implemented by ``ChatConversationBindings`` for peer orchestration.""" + + path: Path + projects: ProjectContextsProtocol | None + + def read(self) -> BindingStateDict: ... + + def observe( + self, + transport_ref: str, + *, + audience: str | None = None, + ) -> BindingPayload: ... + + +class ProjectContextsProtocol(Protocol): + """Protocol matching ``ChatProjectContexts`` consumed by bindings and requests.""" + + workspace_grant: str + conversation_bindings: BindingAuthorityProtocol | None + + def available(self) -> Sequence[BindingPayloadView]: ... + + def session_context(self, session: BindingPayload, /) -> BindingPayload: ... + + +class BindingSessionStoreProtocol(Protocol): + """Protocol matching ``ChatSessionStore`` methods used across bindings.""" + + root: Path + + def list_sessions( + self, + *, + goal_id: str | None = None, + agent_id: str | None = None, + channel_id: str | None = None, + ) -> Sequence[BindingPayload]: ... + + def load_session(self, session_id: str, /) -> BindingPayload | None: ... + + def load_turn( + self, + session_id: str, + turn_id: str, + /, + ) -> BindingPayload | None: ... + + def queued_turns( + self, + session_id: str, + *, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, + ) -> Sequence[BindingPayload]: ... + + def update_session( + self, + session_id: str, + *, + expected_statuses: set[str] | None = None, + expected_upstream_thread_id: str | None = None, + metadata_review: bool = False, + quota_recovery: bool = False, + answer_review_admission: bool = False, + **changes: object, + ) -> BindingPayload: ... + + def read_session_fenced( + self, + session_id: str, + /, + ) -> AbstractContextManager[BindingPayload | None]: ... + + def iter_session_metadata( + self, + *, + goal_id: str | None = None, + agent_id: str | None = None, + channel_id: str | None = None, + ) -> Iterator[tuple[Path, BindingPayload]]: ... + + def public_session(self, payload: BindingPayload, /) -> BindingPayload: ... + + def turn_for_client( + self, + session_id: str, + client_turn_id: str, + /, + ) -> BindingPayload | None: ... + + def create_queued_turn( + self, + session_id: str, + *, + client_turn_id: str, + message: str, + origin: str = "external", + collaboration_request: BindingPayload | None = None, + ) -> tuple[BindingPayload, bool]: ... + + def update_turn( + self, + session_id: str, + turn_id: str, + *, + expected_statuses: set[str] | None = None, + **changes: object, + ) -> BindingPayload | None: ... + + def resumable_session_candidates( + self, + *, + goal_id: str | None, + agent_id: str, + channel_id: str | None = None, + ) -> Sequence[BindingPayload]: ... + + +class BindingControllerProtocol(Protocol): + """Protocol matching ``ChatRuntimeController`` dependencies for bindings.""" + + registry_path: Path | None + coordination_runtime_root: Path + store: ChatSessionStore + + @property + def project_contexts(self) -> ProjectContextsProtocol: ... + + def interrupt_turn( + self, + *, + session_id: str, + turn_id: str, + ) -> BindingPayload: ... + + def resume_session_queue( + self, + *, + session_id: str, + work_dir: Path, + objective: str, + ) -> None: ... + + +class NativeSessionProtocol(Protocol): + """Protocol matching native session dispatch in original conversation execution.""" + + def send( + self, + user_message: str, + /, + *, + project_collaboration: bool = False, + turn_start_guard: Callable[[], AbstractContextManager[None]] | None = None, + on_event: Callable[[str, BindingPayload], None] | None = None, + ) -> BindingPayload: ... + + +def as_binding_payload(value: BindingPayloadView) -> BindingPayload: + """Convert a string-keyed mapping into a plain mutable payload dict.""" + return {str(key): item for key, item in value.items()} + + +def as_binding_row(value: BindingPayloadView) -> BindingRowDict: + """Wrap a binding mapping in ``BindingRowDict`` preserving exact keys.""" + return BindingRowDict({str(key): item for key, item in value.items()}) + + +def as_binding_state(value: BindingPayloadView) -> BindingStateDict: + """Wrap a bindings document in ``BindingStateDict`` preserving exact keys.""" + copied = {str(key): item for key, item in value.items()} + raw_bindings = copied.get("bindings") + if isinstance(raw_bindings, list): + copied["bindings"] = [ + as_binding_row(item) if isinstance(item, Mapping) else item + for item in raw_bindings + ] + return BindingStateDict(copied) + + +def core_effect( + operation: str, + params: BindingPayloadView, + *, + large_local_snapshot: bool = False, +) -> BindingPayload: + """Execute one typed TypeScript Core rule and normalize rejection into ``ValueError``.""" + try: + result = effect_runtime_result( + operation, + dict(params), + large_local_snapshot=large_local_snapshot, + ) + except EffectRuntimeRejected as exc: + raise ValueError(str(exc)) from exc + if not isinstance(result, dict): + raise ValueError("conversation authority returned an invalid result") + return as_binding_payload(result) + + +def session_observation(session: BindingPayloadView) -> BindingPayload: + """Project the exact Session fields evaluated by conversation Core policies.""" + return { + key: session.get(key) + for key in ( + "session_id", + "goal_id", + "agent_id", + "executor_endpoint_id", + "channel_id", + "session_mode", + "status", + "project_context", + "steward_context", + "manager_executor_allocation", + "upstream_context_history", + ) + } + + +def host_ref(session: BindingPayloadView) -> str: + """Compute the opaque 24-hex host reference for an attached session.""" + return hashlib.sha256( + f"{session['host_surface']}\0{session['upstream_thread_id']}".encode() + ).hexdigest()[:24] + + +def host_audiences( + store: BindingSessionStoreProtocol, + session: BindingPayloadView, +) -> list[str]: + """Collect content-free binding stamps across all store sessions for a host.""" + owners: set[str] = set() + for row in store.list_sessions(): + session_id = row.get("session_id") + if not isinstance(session_id, str): + continue + candidate = store.load_session(session_id) + if ( + candidate + and candidate.get("host_surface") == session["host_surface"] + and candidate.get("upstream_thread_id") == session["upstream_thread_id"] + and candidate.get("external_conversation_binding_id") + ): + owners.add(str(candidate["external_conversation_binding_id"])) + return sorted(owners) diff --git a/loopx/capabilities/native_chat/conversation_binding_delivery.py b/loopx/capabilities/native_chat/conversation_binding_delivery.py new file mode 100644 index 0000000000..6c054e1e96 --- /dev/null +++ b/loopx/capabilities/native_chat/conversation_binding_delivery.py @@ -0,0 +1,270 @@ +"""Delivery scope, App steward entry, and input-admission context flows.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from pathlib import Path + +from ...file_lock import exclusive_file_lock +from .conversation_binding_contracts import ( + AppStewardTargetDict, + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingSessionStoreProtocol, + BindingStateDict, + CoreEffectFn, + LockFn, + ReadJsonFn, + ResolvedBindingDict, + session_observation, +) + + +def app_steward_target_flow( + app_steward_session_fn: Callable[[], BindingPayload | None], +) -> AppStewardTargetDict: + session = app_steward_session_fn() + if session is None: + return AppStewardTargetDict({"binding_id": None, "session_id": None}) + steward_context = session["steward_context"] + assert isinstance(steward_context, Mapping) + return AppStewardTargetDict( + { + "binding_id": steward_context["binding_id"], + "session_id": session["session_id"], + } + ) + + +def app_steward_session_flow( + *, + controller: BindingControllerProtocol | None, + read_fn: Callable[[], BindingStateDict], + core_fn: CoreEffectFn, + observe_local_sessions_fn: Callable[ + [str, bool], tuple[BindingStateDict, list[BindingPayload], BindingPayload] + ], + recheck_local_bindings_fn: Callable[[BindingPayloadView], None], +) -> BindingPayload | None: + current = read_fn() + selected = current.get("app_steward_binding_id") + if selected is None: + # Validate legacy state through the same pure owner plan. An + # unreadable grant must not masquerade as an unselected entry. + core_fn( + "collaboration.conversation.binding", + { + "current": current, + "expected_revision": current.get("revision"), + "operation": "select_app_steward", + "binding_id": None, + }, + ) + return None + current, sessions, _ = observe_local_sessions_fn(str(selected), True) + if not sessions: + raise ValueError("the original steward Session is unavailable") + session = max( + sessions, + key=lambda item: ( + str(item.get("last_activity_at") or ""), + str(item["session_id"]), + ), + ) + if controller is None: + raise ValueError("the bound conversation store is unavailable") + # Close uses the same Session fences. Keep it from committing between + # this read and the final grant decision; grant revocation still races + # freely and is detected by the version check. All provider/Core IO has + # already completed, and background grant inspection remains nonblocking. + with controller.store.read_session_fenced(str(session["session_id"])) as fresh: + if fresh is None or fresh.get("status") == "closed": + raise ValueError("the original steward Session is unavailable") + expected = {**session_observation(session), "status": fresh.get("status")} + if session_observation(fresh) != expected: + raise ValueError("the original steward Session is unavailable") + recheck_local_bindings_fn(current) + return fresh + + +@contextmanager +def input_context_flow( + *, + bindings_path: Path, + saved: BindingPayloadView, + origin: str, + session: BindingPayloadView, + store: BindingSessionStoreProtocol, + session_source_fn: Callable[[BindingPayloadView], BindingPayload], + resolve_source_fn: Callable[..., ResolvedBindingDict], + read_fn: Callable[[], BindingStateDict], + resolve_observed_fn: Callable[ + [BindingPayloadView, BindingPayloadView, BindingPayloadView, BindingPayloadView], + BindingPayload, + ], + lock_fn: LockFn = exclusive_file_lock, +) -> Iterator[BindingPayload]: + if origin == "web": + source: BindingPayload = { + "source_ref": saved["source_ref"], + "sender_ref": saved["operator_ref"], + "private_human_message": False, + "origin": "web", + "session_context": saved, + **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {}), + } + elif origin in {"lark", "external"}: + source = session_source_fn(saved) + else: + raise ValueError("unsupported bound conversation input origin") + observed = resolve_source_fn( + binding_id=str(saved["binding_id"]), + source=source, + include_observation=True, + session=session, + ) + with lock_fn(bindings_path, operation="admit_bound_input"): + current = read_fn() + raw_bindings = current.get("bindings") + binding_rows = raw_bindings if isinstance(raw_bindings, list) else [] + if ( + next( + ( + row + for row in binding_rows + if isinstance(row, Mapping) + and row.get("binding_id") == saved["binding_id"] + ), + None, + ) + != observed["binding"] + ): + raise ValueError("conversation binding changed before input admission") + # The provider observation may have waited. Re-read canonical + # identity under the binding fence before Core authorizes input. + fresh = store.load_session(str(session["session_id"])) + if fresh is None: + raise KeyError("chat session was not found") + yield resolve_observed_fn( + current, + observed["binding"], + observed["observation"], + {**source, "session": session_observation(fresh)}, + ) + + +def goal_scope_ids_flow( + controller: BindingControllerProtocol | None, + binding: BindingPayloadView, +) -> list[str]: + if binding.get("goal_scope") != "all_registered": + raw_goal_ids = binding.get("goal_ids", []) + return ( + [str(item) for item in raw_goal_ids] + if isinstance(raw_goal_ids, list) + else [] + ) + from ...control_plane.projects.registry_codec import load_registry + + if controller is None or controller.registry_path is None: + raise ValueError("the steward registry is unavailable") + goals = load_registry(controller.registry_path).get("goals", []) + return [str(goal["id"]) for goal in goals] + + +def delivery_channels_flow( + controller: BindingControllerProtocol | None, + binding: BindingPayloadView, + *, + read_json_fn: ReadJsonFn, +) -> list[str]: + if controller is None: + return [] + from ..manager_context import POLICY_SCHEMA, _root + + path = _root(controller.coordination_runtime_root) / "policy.json" + if not path.exists(): + return [] + policy = read_json_fn(path) + sources = policy.get("sources") + if policy.get("schema_version") != POLICY_SCHEMA or not isinstance(sources, dict): + raise ValueError("invalid manager policy") + prefix = f"manager.external.native.{binding['binding_id']}." + return [ + channel + for channel, source in sources.items() + if channel.startswith(prefix) + and isinstance(source, dict) + and binding["operator_ref"] in source.get("sender_ids", []) + ] + + +def ensure_delivery_scope_flow( + *, + bindings_path: Path, + controller: BindingControllerProtocol | None, + selected: BindingPayloadView, + if_absent: bool, + execute: bool, + read_fn: Callable[[], BindingStateDict], + inner_ensure_fn: Callable[..., None], + lock_fn: LockFn = exclusive_file_lock, +) -> None: + raw_binding = selected["binding"] + if ( + not isinstance(raw_binding, Mapping) + or raw_binding.get("goal_scope") not in {"all_registered", "selected"} + or controller is None + ): + return + with lock_fn(bindings_path, operation="configure_bound_delivery_scope"): + if raw_binding not in read_fn()["bindings"]: + raise ValueError("conversation binding is no longer authorized") + inner_ensure_fn(selected, if_absent=if_absent, execute=execute) + + +def apply_delivery_scope_flow( + controller: BindingControllerProtocol | None, + selected: BindingPayloadView, + *, + if_absent: bool, + execute: bool, +) -> None: + binding = selected["binding"] + if ( + not isinstance(binding, Mapping) + or binding.get("goal_scope") not in {"all_registered", "selected"} + or controller is None + ): + return + from ..manager_context import configure_delivery_scope + + configure_delivery_scope( + controller.coordination_runtime_root, + channel=str(selected["channel_id"]), + local_delivery_scope=str(binding["goal_scope"]), + sender_id=str(binding["operator_ref"]), + execute=execute, + if_absent=if_absent, + ) + + +def session_source(saved: BindingPayloadView) -> BindingPayload: + if saved.get("audience") == "bound_group": + return { + "source_ref": saved["source_ref"], + "sender_ref": saved["operator_ref"], + "private_human_message": False, + "group_ref": saved["group_ref"], + "topic_ref": saved["topic_ref"], + "group_human_message": True, + "session_context": saved, + } + return { + "source_ref": saved["source_ref"], + "sender_ref": saved["operator_ref"], + "private_human_message": True, + "session_context": saved, + **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {}), + } diff --git a/loopx/capabilities/native_chat/conversation_binding_flows.py b/loopx/capabilities/native_chat/conversation_binding_flows.py new file mode 100644 index 0000000000..146927dfb4 --- /dev/null +++ b/loopx/capabilities/native_chat/conversation_binding_flows.py @@ -0,0 +1,619 @@ +"""Publication, resolution, discovery, and target-update flows for conversation bindings.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +from pathlib import Path +import uuid + +from ...file_lock import exclusive_file_lock +from .conversation_binding_contracts import ( + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingRowDict, + BindingStateDict, + CoreEffectFn, + LockFn, + ObserveAudienceFn, + ObserveFn, + ProjectContextsProtocol, + ResolvedBindingDict, + WriteJsonFn, + as_binding_row, + as_binding_state, + session_observation, +) + + +def _require_projects( + projects: ProjectContextsProtocol | None, +) -> ProjectContextsProtocol: + if projects is None: + raise ValueError("bound conversation project contexts are unavailable") + return projects + + +def configure_binding_flow( + *, + bindings_path: Path, + projects: ProjectContextsProtocol | None, + transport_ref: str, + project_ref: str, + executor_endpoint_id: str, + context_kind: str, + project_grant: str | None, + goal_scope: str | None, + audience: str | None, + group_refs: list[str] | None, + available_group_refs: list[str] | None, + expected_provider_ref: str | None, + expected_operator_ref: str | None, + read_fn: Callable[[], BindingStateDict], + observe_fn: ObserveAudienceFn, + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + delivery_channels_fn: Callable[[BindingPayloadView], list[str]], + ensure_delivery_scope_fn: Callable[..., None], + revoke_delivery_sources_fn: Callable[[str], None], + stop_revoked_binding_fn: Callable[[str], None], + lock_fn: LockFn = exclusive_file_lock, +) -> BindingRowDict: + if goal_scope is not None and ( + context_kind != "steward" or goal_scope not in {"selected", "all_registered"} + ): + raise ValueError("select a supported steward Goal scope") + resolved_projects = _require_projects(projects) + if project_grant is None: + project_grant = ( + resolved_projects.workspace_grant + if context_kind == "project" and executor_endpoint_id == "codex" + else "workspace_read" + ) + if project_grant not in {"workspace_read", "workspace_write"} or ( + context_kind != "project" and project_grant != "workspace_read" + ): + raise ValueError("workspace write authorization is only available for project Chat") + observation = observe_fn(transport_ref, audience=audience or "owner") + return _publish_configured_binding( + bindings_path=bindings_path, + projects=resolved_projects, + transport_ref=transport_ref, + project_ref=project_ref, + executor_endpoint_id=executor_endpoint_id, + context_kind=context_kind, + project_grant=project_grant, + goal_scope=goal_scope, + audience=audience, + group_refs=group_refs, + available_group_refs=available_group_refs, + expected_provider_ref=expected_provider_ref, + expected_operator_ref=expected_operator_ref, + observation=observation, + read_fn=read_fn, + core_fn=core_fn, + write_json_fn=write_json_fn, + delivery_channels_fn=delivery_channels_fn, + ensure_delivery_scope_fn=ensure_delivery_scope_fn, + revoke_delivery_sources_fn=revoke_delivery_sources_fn, + stop_revoked_binding_fn=stop_revoked_binding_fn, + lock_fn=lock_fn, + ) + + +def _publish_configured_binding( + *, + bindings_path: Path, + projects: ProjectContextsProtocol, + transport_ref: str, + project_ref: str, + executor_endpoint_id: str, + context_kind: str, + project_grant: str, + goal_scope: str | None, + audience: str | None, + group_refs: list[str] | None, + available_group_refs: list[str] | None, + expected_provider_ref: str | None, + expected_operator_ref: str | None, + observation: BindingPayloadView, + read_fn: Callable[[], BindingStateDict], + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + delivery_channels_fn: Callable[[BindingPayloadView], list[str]], + ensure_delivery_scope_fn: Callable[..., None], + revoke_delivery_sources_fn: Callable[[str], None], + stop_revoked_binding_fn: Callable[[str], None], + lock_fn: LockFn = exclusive_file_lock, +) -> BindingRowDict: + if ( + expected_provider_ref is not None + and observation["provider_ref"] != expected_provider_ref + ): + raise ValueError( + "the selected App changed before binding publication; verify it again" + ) + if ( + expected_operator_ref is not None + and observation["operator_ref"] != expected_operator_ref + ): + raise ValueError( + "the selected owner changed before binding publication; verify it again" + ) + candidate: BindingPayload = { + "schema_version": "loopx_chat_conversation_binding_v0", + "binding_id": uuid.uuid4().hex[:24], + "transport_ref": transport_ref, + "provider_ref": observation["provider_ref"], + "operator_ref": observation["operator_ref"], + "context_kind": context_kind, + "project_ref": project_ref, + "executor_endpoint_id": executor_endpoint_id, + "grant": project_grant if context_kind == "project" else "portfolio_read", + "enabled": True, + **( + {"goal_ids": [], "goal_scope": goal_scope or "all_registered"} + if context_kind == "steward" + else {} + ), + **({"audience": audience} if audience is not None else {}), + **({"group_refs": group_refs} if group_refs is not None else {}), + } + with lock_fn( + bindings_path, operation="configure_chat_conversation_binding" + ): + current = read_fn() + previous = next( + ( + row + for row in current["bindings"] + if row["transport_ref"] == transport_ref + ), + None, + ) + if previous and all( + previous.get(key) == candidate.get(key) + for key in ( + "context_kind", + "project_ref", + "executor_endpoint_id", + "provider_ref", + "operator_ref", + "grant", + "audience", + "group_refs", + ) + ): + if previous.get("agent_targets"): + candidate["agent_targets"] = previous["agent_targets"] + if ( + context_kind == "steward" + and previous + and all( + previous.get(key) == candidate.get(key) + for key in ( + "context_kind", + "project_ref", + "executor_endpoint_id", + "provider_ref", + "operator_ref", + ) + ) + ): + candidate["goal_ids"] = previous["goal_ids"] + # Existing installations retain their exact audience and scope + # until the local operator explicitly changes it. + if goal_scope is None: + candidate.pop("goal_scope", None) + if "goal_scope" in previous: + candidate["goal_scope"] = previous["goal_scope"] + candidate["binding_id"] = previous["binding_id"] + if previous.get("managed_actor") is not None: + candidate["managed_actor"] = previous["managed_actor"] + result = core_fn( + "collaboration.conversation.binding", + { + "current": current, + "expected_revision": current.get("revision"), + "operation": "configure", + "binding": candidate, + "observation": observation, + "available_projects": projects.available(), + **( + {"available_group_refs": available_group_refs} + if audience == "group" + else {} + ), + }, + ) + state_map = result["state"] + assert isinstance(state_map, Mapping) + raw_bindings = state_map["bindings"] + assert isinstance(raw_bindings, list) + proposed = next( + row + for row in raw_bindings + if isinstance(row, Mapping) and row["transport_ref"] == transport_ref + ) + channels = delivery_channels_fn(proposed) if goal_scope is not None else [] + for channel in channels: + ensure_delivery_scope_fn( + {"binding": proposed, "channel_id": channel}, execute=False + ) + # Publish the advertised scope only after every known source policy + # has applied and verified. On IO failure the old binding remains; + # retrying the explicit scope operation converges any earlier source + # writes without making ordinary admission undo a manual restriction. + for channel in channels: + ensure_delivery_scope_fn( + {"binding": proposed, "channel_id": channel}, if_absent=False + ) + if previous and previous["binding_id"] != proposed["binding_id"]: + revoke_delivery_sources_fn(previous["binding_id"]) + if result["changed"] and isinstance(state_map, dict): + write_json_fn(bindings_path, state_map) + readback = read_fn() + if readback != result["state"]: + raise OSError("conversation binding publication did not verify") + binding = next( + row + for row in readback["bindings"] + if row["transport_ref"] == transport_ref + ) + if previous and previous["binding_id"] != binding["binding_id"]: + stop_revoked_binding_fn(previous["binding_id"]) + return as_binding_row(binding) + + +def disconnect_binding_flow( + *, + bindings_path: Path, + binding_id: str, + expected_revision: int, + read_fn: Callable[[], BindingStateDict], + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + revoke_delivery_sources_fn: Callable[[str], None], + stop_revoked_binding_fn: Callable[[str], None], + lock_fn: LockFn = exclusive_file_lock, +) -> BindingStateDict: + with lock_fn( + bindings_path, operation="disconnect_chat_conversation_binding" + ): + result = core_fn( + "collaboration.conversation.binding", + { + "current": read_fn(), + "expected_revision": expected_revision, + "operation": "disconnect", + "binding_id": binding_id, + }, + ) + revoke_delivery_sources_fn(binding_id) + state_map = result["state"] + if result["changed"] and isinstance(state_map, dict): + write_json_fn(bindings_path, state_map) + if read_fn() != result["state"]: + raise OSError("conversation binding revocation did not verify") + stop_revoked_binding_fn(binding_id) + assert isinstance(state_map, Mapping) + return as_binding_state(state_map) + + +def select_app_steward_flow( + *, + bindings_path: Path, + binding_id: str | None, + expected_revision: int, + projects: ProjectContextsProtocol | None, + read_fn: Callable[[], BindingStateDict], + observe_fn: ObserveFn, + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + lock_fn: LockFn = exclusive_file_lock, +) -> BindingStateDict: + row = next( + (item for item in read_fn()["bindings"] if item["binding_id"] == binding_id), + None, + ) + observation = observe_fn(row["transport_ref"]) if row is not None else None + available = _require_projects(projects).available() if binding_id is not None else [] + with lock_fn(bindings_path, operation="select_app_steward"): + result = core_fn( + "collaboration.conversation.binding", + { + "current": read_fn(), + "expected_revision": expected_revision, + "operation": "select_app_steward", + "binding_id": binding_id, + "observation": observation, + "available_projects": available, + }, + ) + state_map = result["state"] + if result["changed"] and isinstance(state_map, dict): + write_json_fn(bindings_path, state_map) + if read_fn() != result["state"]: + raise OSError("App steward selection did not verify") + assert isinstance(state_map, Mapping) + return as_binding_state(state_map) + + +def find_binding_row( + state: BindingPayloadView, binding_id: str +) -> BindingPayloadView | None: + raw_bindings = state.get("bindings") + rows = raw_bindings if isinstance(raw_bindings, list) else [] + return next( + ( + item + for item in rows + if isinstance(item, Mapping) and item.get("binding_id") == binding_id + ), + None, + ) + + +def build_resolved_binding( + *, + current: BindingPayloadView, + row: BindingPayloadView, + observation: BindingPayload, + resolve_observed_fn: Callable[ + [BindingPayloadView, BindingPayloadView, BindingPayloadView, BindingPayloadView], + BindingPayload, + ], + source_ref: str, + sender_ref: str, + private_human_message: bool, + session_context: BindingPayloadView | None, + group_ref: str | None, + topic_ref: str | None, + group_human_message: bool, + include_observation: bool, + origin: str | None, + session: BindingPayloadView | None, +) -> ResolvedBindingDict: + selected = resolve_observed_fn( + current, + row, + observation, + { + "source_ref": source_ref, + "sender_ref": sender_ref, + "private_human_message": private_human_message, + **({"origin": origin} if origin is not None else {}), + **( + {"session_context": session_context} + if session_context is not None + else {} + ), + **({"session": session_observation(session)} if session is not None else {}), + **({"group_ref": group_ref} if group_ref is not None else {}), + **({"topic_ref": topic_ref} if topic_ref is not None else {}), + **( + {"group_human_message": group_human_message} + if group_ref is not None or group_human_message + else {} + ), + }, + ) + # Presentation may need the name from this exact verified read. Keep it + # outside the persisted context and opt-in; it is never a cached grant + # or a substitute for the next admission/delivery owner's fresh check. + if include_observation: + return ResolvedBindingDict({**selected, "observation": observation}) + return ResolvedBindingDict(selected) + + +def observe_local_sessions_flow( + *, + binding_id: str, + app_steward_entry: bool, + controller: BindingControllerProtocol | None, + projects: ProjectContextsProtocol | None, + read_fn: Callable[[], BindingStateDict], + observe_fn: ObserveFn, + core_fn: CoreEffectFn, + goal_scope_ids_fn: Callable[[BindingPayloadView], list[str]], +) -> tuple[BindingStateDict, list[BindingPayload], BindingPayload]: + if controller is None: + raise ValueError("the bound conversation store is unavailable") + row = next( + (item for item in read_fn()["bindings"] if item["binding_id"] == binding_id), + None, + ) + if row is None: + raise ValueError("conversation binding is no longer authorized") + observation = dict(observe_fn(row["transport_ref"])) + store = controller.store + + def mentions_binding(session: BindingPayloadView) -> bool: + return any( + isinstance(ctx := session.get(key), dict) + and ctx.get("binding_id") == binding_id + for key in ("project_context", "steward_context") + ) + + # Keep aliases in the candidate set even when their own metadata is + # unrelated. Core must still see duplicate canonical Session identities. + hints = ( + session + for path, session in store.iter_session_metadata() + if path.parent.name != session["session_id"] or mentions_binding(session) + ) + sessions: list[BindingPayload] = [] + for hint in sorted( + hints, key=lambda item: str(item.get("updated_at") or ""), reverse=True + ): + session = store.load_session(str(hint["session_id"])) + if session and mentions_binding(session): + sessions.append(session) + current = read_fn() + if ( + next( + (item for item in current["bindings"] if item["binding_id"] == binding_id), + None, + ) + != row + ): + raise ValueError("conversation binding changed during identity verification") + available = _require_projects(projects).available() + result = core_fn( + "collaboration.conversation.local_sessions", + { + "current": current, + "binding_id": binding_id, + "observation": observation, + "available_projects": available, + "sessions": [session_observation(session) for session in sessions], + **({"app_steward_entry": True} if app_steward_entry else {}), + **( + {"available_goal_ids": goal_scope_ids_fn(row)} + if row.get("goal_scope") == "all_registered" + else {} + ), + }, + ) + by_id = {str(session["session_id"]): session for session in sessions} + project = next( + project for project in available if project["project_ref"] == row["project_ref"] + ) + source: BindingPayload = { + "binding_id": binding_id, + "app_ref": row["transport_ref"], + "context_kind": row["context_kind"], + "audience": row.get("audience", "owner"), + "project_title": Path(str(project["workspace_path"])).name, + "context_available": True, + "executor_endpoint_id": row["executor_endpoint_id"], + } + raw_session_ids = result["session_ids"] + assert isinstance(raw_session_ids, list) + return current, [by_id[str(sid)] for sid in raw_session_ids], source + + +def adopt_created_goal_flow( + *, + bindings_path: Path, + binding_id: str, + source: BindingPayloadView, + proposal: BindingPayloadView, + goal: BindingPayloadView, + resolve_source_fn: Callable[[str, BindingPayloadView], ResolvedBindingDict], + read_fn: Callable[[], BindingStateDict], + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + lock_fn: LockFn = exclusive_file_lock, +) -> None: + selected = resolve_source_fn(binding_id, source) + with lock_fn(bindings_path, operation="adopt_steward_created_goal"): + current = read_fn() + result = core_fn( + "collaboration.conversation.binding", + { + "current": current, + "expected_revision": current["revision"], + "operation": "adopt_created_goal", + "binding_id": binding_id, + "context": selected["context"], + "proposal": proposal, + "goal": { + "goal_id": goal["id"], + "workspace_path": str(Path(str(goal["repo"])).resolve()), + "creation_operation_id": goal.get("creation_operation_id"), + }, + }, + ) + state_map = result["state"] + if result["changed"] and isinstance(state_map, dict): + write_json_fn(bindings_path, state_map) + if read_fn() != result["state"]: + raise OSError("steward scope publication did not verify") + + +def change_agent_target_flow( + *, + bindings_path: Path, + binding_id: str, + expected_revision: int, + session_id: str | None, + target_ref: str | None, + controller: BindingControllerProtocol | None, + projects: ProjectContextsProtocol | None, + read_fn: Callable[[], BindingStateDict], + observe_fn: ObserveFn, + observe_agent_fn: Callable[[str], BindingPayload], + core_fn: CoreEffectFn, + write_json_fn: WriteJsonFn, + lock_fn: LockFn = exclusive_file_lock, +) -> BindingStateDict: + row = next( + (item for item in read_fn()["bindings"] if item["binding_id"] == binding_id), + None, + ) + if row is None: + raise ValueError("conversation binding is no longer authorized") + # Provider IO must not prevent disconnect from publishing revocation. + # Recheck the exact binding under its fence before using this observation. + observation = observe_fn(row["transport_ref"]) + with lock_fn( + bindings_path, operation="configure_conversation_agent_target" + ): + current = read_fn() + if ( + next( + ( + item + for item in current["bindings"] + if item["binding_id"] == binding_id + ), + None, + ) + != row + ): + raise ValueError("conversation binding changed during identity verification") + params: BindingPayload = { + "current": current, + "expected_revision": expected_revision, + "binding_id": binding_id, + "observation": observation, + "available_projects": _require_projects(projects).available(), + } + if session_id is not None: + observed = observe_agent_fn(session_id) + observed_session = observed["session"] + assert isinstance(observed_session, Mapping) + target = { + key: observed_session.get(key) + for key in ( + "session_id", + "goal_id", + "goal_instance_id", + "agent_id", + "executor_endpoint_id", + ) + } + params.update( + operation="grant_agent_target", + target={ + "target_ref": uuid.uuid4().hex[:24], + "host_ref": observed["host_ref"], + **target, + }, + target_observation=observed, + ) + else: + params.update(operation="revoke_agent_target", target_ref=target_ref) + result = core_fn("collaboration.conversation.binding", params) + state_map = result["state"] + if result["changed"] and isinstance(state_map, dict): + if session_id is not None: + assert controller is not None + controller.store.update_session( + session_id, external_conversation_binding_id=binding_id + ) + write_json_fn(bindings_path, state_map) + if read_fn() != result["state"]: + raise OSError("Agent target grant publication did not verify") + assert isinstance(state_map, Mapping) + return as_binding_state(state_map) diff --git a/loopx/capabilities/native_chat/conversation_bindings.py b/loopx/capabilities/native_chat/conversation_bindings.py index c31276f147..79678d7df0 100644 --- a/loopx/capabilities/native_chat/conversation_bindings.py +++ b/loopx/capabilities/native_chat/conversation_bindings.py @@ -6,1155 +6,625 @@ """ from __future__ import annotations -from collections.abc import Callable, Iterator, Mapping +from collections.abc import Iterator, Mapping from contextlib import contextmanager -import logging from pathlib import Path -from typing import TYPE_CHECKING, Any -import uuid -import hashlib -from ...chat_store import TERMINAL_TURN_STATES, _atomic_write_json, _read_json -from ...control_plane.effect_runtime import ( - EffectRuntimeRejected, effect_runtime_request_scope, effect_runtime_result, +from ...chat_store import ( + _atomic_write_json as _atomic_write_json, + _read_json as _read_json, +) +from ...control_plane.effect_runtime import effect_runtime_request_scope +from ...file_lock import exclusive_file_lock as exclusive_file_lock +from .conversation_binding_agents import ( + agent_candidates_flow, + agent_observation_flow, + reconcile_steward_executor_flow, + reconcile_steward_executors_flow, + stop_recoveries_flow, + stop_revoked_binding_flow, + validate_external_agent_turn_flow, +) +from .conversation_binding_contracts import ( + AppStewardTargetDict as AppStewardTargetDict, + BindingAuthorityProtocol as BindingAuthorityProtocol, + BindingControllerProtocol as BindingControllerProtocol, + BindingPayload as BindingPayload, + BindingPayloadView as BindingPayloadView, + BindingRowDict as BindingRowDict, + BindingSessionStoreProtocol as BindingSessionStoreProtocol, + BindingStateDict as BindingStateDict, + LocalSessionSnapshotDict as LocalSessionSnapshotDict, + ObserveFn as ObserveFn, + ProjectContextsProtocol as ProjectContextsProtocol, + ResolvedBindingDict as ResolvedBindingDict, + as_binding_payload, + as_binding_state, + core_effect, + host_audiences, + host_ref, + session_observation, +) +from .conversation_binding_delivery import ( + app_steward_session_flow, + app_steward_target_flow, + apply_delivery_scope_flow, + delivery_channels_flow, + ensure_delivery_scope_flow, + goal_scope_ids_flow, + input_context_flow, + session_source, +) +from .conversation_binding_flows import ( + adopt_created_goal_flow, + build_resolved_binding, + change_agent_target_flow, + configure_binding_flow, + disconnect_binding_flow, + find_binding_row, + observe_local_sessions_flow, + select_app_steward_flow, +) +from .original_conversation_requests import ( + OriginalConversationRequests as OriginalConversationRequests, ) -from ...file_lock import exclusive_file_lock -if TYPE_CHECKING: - from ...chat_store import ChatSessionStore +def _host_ref(session: BindingPayloadView) -> str: + return host_ref(session) -class ChatConversationBindings: - def __init__(self, *, root: Path, project_contexts: Any, - observe: Callable[[str], dict[str, Any]], - observe_group: Callable[[str], dict[str, Any]] | None = None) -> None: - self.path = root / "conversation-bindings.json" - self.projects = project_contexts - self._observe_owner = observe - self._observe_group = observe_group - self.controller: Any | None = None - def observe(self, transport_ref: str, *, audience: str | None = None) -> dict[str, Any]: - row: dict[str, Any] = next((item for item in self.read()["bindings"] if item["transport_ref"] == transport_ref), {}) +def _host_audiences( + store: BindingSessionStoreProtocol, session: BindingPayloadView +) -> list[str]: + return host_audiences(store, session) + + +class ChatConversationBindings: + """Durable store and boundary orchestrator for bound Chat conversations.""" + + def __init__( + self, + *, + root: Path, + project_contexts: ProjectContextsProtocol | None, + observe: ObserveFn, + observe_group: ObserveFn | None = None, + ) -> None: + self.path: Path = root / "conversation-bindings.json" + self.projects: ProjectContextsProtocol | None = project_contexts + self._observe_owner: ObserveFn = observe + self._observe_group: ObserveFn | None = observe_group + self.controller: BindingControllerProtocol | None = None + + def _require_projects(self) -> ProjectContextsProtocol: + if self.projects is None: + raise ValueError("bound conversation project contexts are unavailable") + return self.projects + + def observe( + self, + transport_ref: str, + *, + audience: str | None = None, + ) -> BindingPayload: + row: BindingPayloadView = next( + ( + item + for item in self.read()["bindings"] + if item["transport_ref"] == transport_ref + ), + {}, + ) if audience is None: - audience = row.get("audience", "owner") + raw_audience = row.get("audience", "owner") + audience = raw_audience if isinstance(raw_audience, str) else None if audience == "group" and self._observe_group is not None: - observed = self._observe_group(transport_ref) + observed = as_binding_payload(self._observe_group(transport_ref)) # Earlier group grants used the verified user's principal. Keep # that exact identity/home until an explicit disconnect/reconnect; # changing it during a poll would invalidate resumed Sessions. - if (row.get("audience") == "group" and row.get("provider_ref") == observed["provider_ref"] - and row.get("operator_ref") != observed["operator_ref"]): - return self._observe_owner(transport_ref) + if ( + row.get("audience") == "group" + and row.get("provider_ref") == observed["provider_ref"] + and row.get("operator_ref") != observed["operator_ref"] + ): + return as_binding_payload(self._observe_owner(transport_ref)) return observed - return self._observe_owner(transport_ref) + return as_binding_payload(self._observe_owner(transport_ref)) - def read(self) -> dict[str, Any]: + def read(self) -> BindingStateDict: if not self.path.exists(): - return {"schema_version": "loopx_chat_conversation_bindings_v0", "revision": 0, "bindings": []} + return BindingStateDict( + { + "schema_version": "loopx_chat_conversation_bindings_v0", + "revision": 0, + "bindings": [], + } + ) # An unreadable existing grant is not an empty configuration to overwrite. - return _read_json(self.path) + return as_binding_state(_read_json(self.path)) @staticmethod - def _core(operation: str, params: dict[str, Any], *, large_local_snapshot: bool = False) -> dict[str, Any]: - try: - result = effect_runtime_result(operation, params, large_local_snapshot=large_local_snapshot) - except EffectRuntimeRejected as exc: - raise ValueError(str(exc)) from exc - if not isinstance(result, dict): - raise ValueError("conversation authority returned an invalid result") - return result - - def configure(self, *, transport_ref: str, project_ref: str, - executor_endpoint_id: str, context_kind: str = "project", - project_grant: str | None = None, goal_scope: str | None = None, - audience: str | None = None, group_refs: list[str] | None = None, - available_group_refs: list[str] | None = None, - expected_provider_ref: str | None = None, - expected_operator_ref: str | None = None) -> dict[str, Any]: - if goal_scope is not None and (context_kind != "steward" or goal_scope not in {"selected", "all_registered"}): - raise ValueError("select a supported steward Goal scope") - if project_grant is None: - project_grant = self.projects.workspace_grant if context_kind == "project" and executor_endpoint_id == "codex" else "workspace_read" - if project_grant not in {"workspace_read", "workspace_write"} or (context_kind != "project" and project_grant != "workspace_read"): - raise ValueError("workspace write authorization is only available for project Chat") - observation = self.observe(transport_ref, audience=audience or "owner") - if expected_provider_ref is not None and observation["provider_ref"] != expected_provider_ref: - raise ValueError("the selected App changed before binding publication; verify it again") - if expected_operator_ref is not None and observation["operator_ref"] != expected_operator_ref: - raise ValueError("the selected owner changed before binding publication; verify it again") - candidate = { - "schema_version": "loopx_chat_conversation_binding_v0", - "binding_id": uuid.uuid4().hex[:24], "transport_ref": transport_ref, - "provider_ref": observation["provider_ref"], "operator_ref": observation["operator_ref"], - "context_kind": context_kind, "project_ref": project_ref, - "executor_endpoint_id": executor_endpoint_id, - "grant": project_grant if context_kind == "project" else "portfolio_read", "enabled": True, - **({"goal_ids": [], "goal_scope": goal_scope or "all_registered"} if context_kind == "steward" else {}), - **({"audience": audience} if audience is not None else {}), - **({"group_refs": group_refs} if group_refs is not None else {}), - } - with exclusive_file_lock(self.path, operation="configure_chat_conversation_binding"): - current = self.read() - previous = next((row for row in current["bindings"] if row["transport_ref"] == transport_ref), None) - if previous and all(previous.get(key) == candidate.get(key) for key in ["context_kind", "project_ref", "executor_endpoint_id", "provider_ref", "operator_ref", "grant", "audience", "group_refs"]): - if previous.get("agent_targets"): - candidate["agent_targets"] = previous["agent_targets"] - if (context_kind == "steward" and previous and all(previous.get(key) == candidate.get(key) - for key in ["context_kind", "project_ref", "executor_endpoint_id", "provider_ref", "operator_ref"])): - candidate["goal_ids"] = previous["goal_ids"] - # Existing installations retain their exact audience and scope - # until the local operator explicitly changes it. - if goal_scope is None: - candidate.pop("goal_scope", None) - if "goal_scope" in previous: - candidate["goal_scope"] = previous["goal_scope"] - candidate["binding_id"] = previous["binding_id"] - if previous.get("managed_actor") is not None: - candidate["managed_actor"] = previous["managed_actor"] - result = self._core("collaboration.conversation.binding", { - "current": current, "expected_revision": current.get("revision"), "operation": "configure", - "binding": candidate, "observation": observation, "available_projects": self.projects.available(), - **({"available_group_refs": available_group_refs} if audience == "group" else {}), - }) - proposed = next(row for row in result["state"]["bindings"] if row["transport_ref"] == transport_ref) - channels = self.delivery_channels(proposed) if goal_scope is not None else [] - for channel in channels: - self._ensure_delivery_scope({"binding": proposed, "channel_id": channel}, execute=False) - # Publish the advertised scope only after every known source policy - # has applied and verified. On IO failure the old binding remains; - # retrying the explicit scope operation converges any earlier source - # writes without making ordinary admission undo a manual restriction. - for channel in channels: - self._ensure_delivery_scope({"binding": proposed, "channel_id": channel}, if_absent=False) - if previous and previous["binding_id"] != proposed["binding_id"]: - self._revoke_delivery_sources(previous["binding_id"]) - if result["changed"]: - _atomic_write_json(self.path, result["state"]) - readback = self.read() - if readback != result["state"]: - raise OSError("conversation binding publication did not verify") - binding: dict[str, Any] = next(row for row in readback["bindings"] if row["transport_ref"] == transport_ref) - if previous and previous["binding_id"] != binding["binding_id"]: - self._stop_revoked_binding(previous["binding_id"]) - return binding - - def disconnect(self, binding_id: str, *, expected_revision: int) -> dict[str, Any]: - with exclusive_file_lock(self.path, operation="disconnect_chat_conversation_binding"): - result = self._core("collaboration.conversation.binding", { - "current": self.read(), "expected_revision": expected_revision, - "operation": "disconnect", "binding_id": binding_id, - }) - self._revoke_delivery_sources(binding_id) - if result["changed"]: - _atomic_write_json(self.path, result["state"]) - if self.read() != result["state"]: - raise OSError("conversation binding revocation did not verify") - self._stop_revoked_binding(binding_id) - return dict(result["state"]) - - def select_app_steward(self, binding_id: str | None, *, expected_revision: int) -> dict[str, Any]: + def _core( + operation: str, + params: BindingPayloadView, + *, + large_local_snapshot: bool = False, + ) -> BindingPayload: + return core_effect( + operation, params, large_local_snapshot=large_local_snapshot + ) + + def configure( + self, + *, + transport_ref: str, + project_ref: str, + executor_endpoint_id: str, + context_kind: str = "project", + project_grant: str | None = None, + goal_scope: str | None = None, + audience: str | None = None, + group_refs: list[str] | None = None, + available_group_refs: list[str] | None = None, + expected_provider_ref: str | None = None, + expected_operator_ref: str | None = None, + ) -> BindingRowDict: + return configure_binding_flow( + bindings_path=self.path, + projects=self.projects, + transport_ref=transport_ref, + project_ref=project_ref, + executor_endpoint_id=executor_endpoint_id, + context_kind=context_kind, + project_grant=project_grant, + goal_scope=goal_scope, + audience=audience, + group_refs=group_refs, + available_group_refs=available_group_refs, + expected_provider_ref=expected_provider_ref, + expected_operator_ref=expected_operator_ref, + read_fn=self.read, + observe_fn=self.observe, + core_fn=self._core, + write_json_fn=_atomic_write_json, + delivery_channels_fn=self.delivery_channels, + ensure_delivery_scope_fn=self._ensure_delivery_scope, + revoke_delivery_sources_fn=self._revoke_delivery_sources, + stop_revoked_binding_fn=self._stop_revoked_binding, + lock_fn=exclusive_file_lock, + ) + + def disconnect( + self, binding_id: str, *, expected_revision: int + ) -> BindingStateDict: + return disconnect_binding_flow( + bindings_path=self.path, + binding_id=binding_id, + expected_revision=expected_revision, + read_fn=self.read, + core_fn=self._core, + write_json_fn=_atomic_write_json, + revoke_delivery_sources_fn=self._revoke_delivery_sources, + stop_revoked_binding_fn=self._stop_revoked_binding, + lock_fn=exclusive_file_lock, + ) + + def select_app_steward( + self, binding_id: str | None, *, expected_revision: int + ) -> BindingStateDict: """Select one existing source for the App entry without changing grants.""" - row = next((item for item in self.read()["bindings"] if item["binding_id"] == binding_id), None) - observation = self.observe(row["transport_ref"]) if row is not None else None - with exclusive_file_lock(self.path, operation="select_app_steward"): - result = self._core("collaboration.conversation.binding", { - "current": self.read(), "expected_revision": expected_revision, - "operation": "select_app_steward", "binding_id": binding_id, - "observation": observation, "available_projects": self.projects.available() if binding_id is not None else [], - }) - if result["changed"]: - _atomic_write_json(self.path, result["state"]) - if self.read() != result["state"]: - raise OSError("App steward selection did not verify") - return dict(result["state"]) + return select_app_steward_flow( + bindings_path=self.path, + binding_id=binding_id, + expected_revision=expected_revision, + projects=self.projects, + read_fn=self.read, + observe_fn=self.observe, + core_fn=self._core, + write_json_fn=_atomic_write_json, + lock_fn=exclusive_file_lock, + ) def reconcile_steward_executors(self) -> None: """Publish a previously adopted machine executor at Chat startup.""" - from ...chat_manager import steward_machine_defaults - - controller = self.controller - if controller is None: - return - defaults = steward_machine_defaults(controller) - if (not defaults or defaults.get("status") != "ready" - or defaults.get("source") != "machine_configuration" - or defaults.get("selection_policy") not in {"preferred", "pinned"} - or defaults.get("executor_endpoint") not in {"antigravity", "codex"}): - return - try: - rows = self.read()["bindings"] - if not isinstance(rows, list): - raise ValueError("invalid conversation bindings state") - except (OSError, ValueError, KeyError) as exc: - logging.getLogger(__name__).warning("Steward bindings unavailable for reconciliation (%s)", type(exc).__name__) + reconcile_steward_executors_flow( + controller=self.controller, + read_fn=self.read, + reconcile_one_fn=self._reconcile_steward_executor, + ) + + def _reconcile_steward_executor( + self, row: BindingPayloadView, defaults: BindingPayloadView + ) -> None: + if self.controller is None: return - for row in rows: - if (not isinstance(row, dict) or row.get("context_kind") != "steward" - or row.get("audience", "owner") != "owner" - or row.get("enabled") is not True - or row.get("executor_endpoint_id") not in {"antigravity", "codex"} - or row.get("executor_endpoint_id") == defaults["executor_endpoint"]): - continue - try: - self._reconcile_steward_executor(row, defaults) - except (OSError, ValueError, TypeError, KeyError, RuntimeError) as exc: - logging.getLogger(__name__).warning("Steward executor reconciliation held (%s)", type(exc).__name__) - - def _reconcile_steward_executor(self, row: dict[str, Any], defaults: Mapping[str, Any]) -> None: - from ...chat_manager import manager_executor_allocation, steward_machine_defaults - from ..machine_configuration.builtins import build_builtin_machine_configuration_registry - from ..machine_configuration.store import machine_configuration_revision, read_machine_configuration - from ..steward_executor.allocation import normalize_manager_executor_allocation - from ..steward_executor.machine_defaults import effective_steward_executor_defaults - - store = self.controller.store - binding_id = row["binding_id"] - endpoint = defaults["executor_endpoint"] - channel_prefix = f"manager.external.native.{binding_id}." - all_open = [s for s in store.list_sessions() - if s.get("channel_id", "").startswith(channel_prefix) and s.get("status") != "closed"] - candidates = [s for s in all_open if not (s.get("steward_context") or {}).get("topic_ref")] - if (len(candidates) != 1 or candidates[0].get("agent_id") != endpoint or candidates[0].get("status") != "ready" - or any(s.get("status") != "ready" or s.get("active_turn_id") is not None for s in all_open)): - return # Defaults alone do not retarget an existing session. - observation = self.observe(row["transport_ref"]) - with exclusive_file_lock(self.path, operation="reconcile_steward_executor"): - current = self.read() - if row not in current["bindings"] or steward_machine_defaults(self.controller) != defaults: - return - session = store.load_session(candidates[0]["session_id"]) - saved = (session or {}).get("steward_context") - stored = (session or {}).get("manager_executor_allocation") - if (not session or not isinstance(saved, dict) or not isinstance(stored, dict) - or session.get("status") != "ready" or session.get("active_turn_id") is not None - or session.get("agent_id") != endpoint or session.get("executor_endpoint_id") != endpoint - or stored.get("selection_policy") != defaults["selection_policy"] - or store.queued_turns(session["session_id"], strict=True, include_reserved=True)): - return - allocation = None - if stored.get("configuration_revision") == defaults.get("configuration_revision"): - try: - allocation = normalize_manager_executor_allocation(stored) - except (TypeError, ValueError): - pass - else: - # A machine configuration transaction records the revision of - # the whole document. Match that exact basis before projecting - # it to the narrower revision used by steward allocations. - configuration = read_machine_configuration(store.root.parent, - registry=build_builtin_machine_configuration_registry()) - if (not configuration or machine_configuration_revision(configuration) != stored.get("configuration_revision") - or effective_steward_executor_defaults(configuration) != defaults): - return - if allocation is None: - allocation = manager_executor_allocation(self.controller, machine_defaults=defaults) - expected = {**self._session_observation(session), "manager_executor_allocation": allocation, - "active_turn_id": session.get("active_turn_id"), "agent_model_id": session.get("agent_model_id"), - "agent_reasoning_effort": session.get("agent_reasoning_effort")} - result = self._core("collaboration.conversation.binding", { - "current": current, "expected_revision": current["revision"], "operation": "reconcile_steward_executor", - "binding_id": binding_id, "observation": observation, "available_projects": self.projects.available(), - "available_goal_ids": self.goal_scope_ids(row), "machine_defaults": dict(defaults), - "session": expected, "queue_empty": True, - }) - if stored != allocation: - store.update_session(session["session_id"], expected_statuses={"ready"}, - expected_upstream_thread_id=session.get("upstream_thread_id"), manager_executor_allocation=allocation) - fresh = store.load_session(session["session_id"]) - if (not fresh or any(fresh.get(key) != value for key, value in expected.items()) - or store.queued_turns(session["session_id"], strict=True, include_reserved=True) - or steward_machine_defaults(self.controller) != defaults): - return - if result["changed"]: - _atomic_write_json(self.path, result["state"], preserve_mode=True) - if self.read() != result["state"]: - raise OSError("steward executor binding publication did not verify") - - def app_steward_target(self) -> dict[str, Any]: - session = self.app_steward_session() - if session is None: - return {"binding_id": None, "session_id": None} - return {"binding_id": session["steward_context"]["binding_id"], "session_id": session["session_id"]} - - def app_steward_session(self) -> dict[str, Any] | None: + reconcile_steward_executor_flow( + bindings_path=self.path, + controller=self.controller, + projects=self._require_projects(), + row=row, + defaults=defaults, + read_fn=self.read, + observe_fn=self.observe, + core_fn=self._core, + write_json_fn=_atomic_write_json, + goal_scope_ids_fn=self.goal_scope_ids, + lock_fn=exclusive_file_lock, + ) + + def app_steward_target(self) -> AppStewardTargetDict: + return app_steward_target_flow(self.app_steward_session) + + def app_steward_session(self) -> BindingPayload | None: """Read the Session within the selected source without starting work.""" - current = self.read() - selected = current.get("app_steward_binding_id") - if selected is None: - # Validate legacy state through the same pure owner plan. An - # unreadable grant must not masquerade as an unselected entry. - self._core("collaboration.conversation.binding", {"current": current, - "expected_revision": current.get("revision"), "operation": "select_app_steward", "binding_id": None}) - return None - current, sessions, _ = self._observe_local_sessions(selected, app_steward_entry=True) - if not sessions: - raise ValueError("the original steward Session is unavailable") - session = max(sessions, key=lambda item: (item.get("last_activity_at") or "", item["session_id"])) - # Close uses the same Session fences. Keep it from committing between - # this read and the final grant decision; grant revocation still races - # freely and is detected by the version check. All provider/Core IO has - # already completed, and background grant inspection remains nonblocking. - with self.controller.store.read_session_fenced(session["session_id"]) as fresh: - if fresh is None or fresh.get("status") == "closed": - raise ValueError("the original steward Session is unavailable") - expected = {**self._session_observation(session), "status": fresh.get("status")} - if self._session_observation(fresh) != expected: - raise ValueError("the original steward Session is unavailable") - self._recheck_local_bindings(current) - return fresh + return app_steward_session_flow( + controller=self.controller, + read_fn=self.read, + core_fn=self._core, + observe_local_sessions_fn=lambda bid, app_entry: self._observe_local_sessions( + bid, app_steward_entry=app_entry + ), + recheck_local_bindings_fn=self._recheck_local_bindings, + ) def _revoke_delivery_sources(self, binding_id: str) -> None: if self.controller is not None: from ..manager_context import revoke_conversation_sources - revoke_conversation_sources(self.controller.coordination_runtime_root, binding_id) - - def _stop_revoked_binding(self, binding_id: str) -> None: - """Apply the committed grant decision through existing exact Turn control. - Never wait for a worker while holding the grant publication fence. Drop - its queued work before stopping the active Turn; other audiences and - local Turns in a shared attached Session retain their own authority. - Retrying disconnect with the current revision retries an unconfirmed stop. - """ - if self.controller is None: - return - store = self.controller.store - failures = [] - for row in store.list_sessions(): - session = store.load_session(row["session_id"]) - if session is None: - continue - bound = any(isinstance(session.get(key), dict) - and session[key].get("binding_id") == binding_id - for key in ("project_context", "steward_context")) - turns = store.queued_turns(session["session_id"]) - active = store.load_turn(session["session_id"], session["active_turn_id"]) if session.get("active_turn_id") else None - if active: - turns.append(active) - for turn in turns: - target = turn.get("external_agent_target") or {} - if (not bound and (target.get("context") or {}).get("binding_id") != binding_id - or turn.get("status") in TERMINAL_TURN_STATES): - continue - try: - stopped = self.controller.interrupt_turn(session_id=session["session_id"], turn_id=turn["turn_id"]) - if stopped.get("status") not in TERMINAL_TURN_STATES: - raise RuntimeError("Turn stop did not settle") - except Exception as exc: - # Revocation remains published even when a host lacks stop - # control. Continue stopping other exact targets, then report - # failure without exposing private transport diagnostics. - failures.append(exc) - if failures: - raise OSError("Conversation grant revoked; execution stop is not confirmed. Retry stop for this binding.") from failures[0] + revoke_conversation_sources( + self.controller.coordination_runtime_root, binding_id + ) - def resolve(self, *, binding_id: str, source_ref: str, sender_ref: str, - private_human_message: bool, session_context: dict[str, Any] | None = None, - group_ref: str | None = None, topic_ref: str | None = None, - group_human_message: bool = False, include_observation: bool = False, - origin: str | None = None, session: dict[str, Any] | None = None) -> dict[str, Any]: - current = self.read() - row = next((item for item in current.get("bindings", []) if item.get("binding_id") == binding_id), None) + def _stop_revoked_binding(self, binding_id: str) -> None: + """Apply the committed grant decision through existing exact Turn control.""" + stop_revoked_binding_flow(self.controller, binding_id) + + def resolve( + self, + *, + binding_id: str, + source_ref: str, + sender_ref: str, + private_human_message: bool, + session_context: BindingPayloadView | None = None, + group_ref: str | None = None, + topic_ref: str | None = None, + group_human_message: bool = False, + include_observation: bool = False, + origin: str | None = None, + session: BindingPayloadView | None = None, + ) -> ResolvedBindingDict: + row = find_binding_row(self.read(), binding_id) if row is None: raise ValueError("conversation binding is no longer authorized") - observation = dict(self.observe(row["transport_ref"])) + observation = dict(self.observe(str(row["transport_ref"]))) # Provider verification can wait on IO. It cannot authorize a binding # that was revoked or replaced while that observation was in flight. # Unrelated binding changes do not invalidate this exact source. current = self.read() - if next((item for item in current.get("bindings", []) - if item.get("binding_id") == binding_id), None) != row: + if find_binding_row(current, binding_id) != row: raise ValueError("conversation binding changed during identity verification") - selected = self._resolve_observed(current, row, observation, { - "source_ref": source_ref, "sender_ref": sender_ref, "private_human_message": private_human_message, - **({"origin": origin} if origin is not None else {}), - **({"session_context": session_context} if session_context is not None else {}), - **({"session": self._session_observation(session)} if session is not None else {}), - **({"group_ref": group_ref} if group_ref is not None else {}), - **({"topic_ref": topic_ref} if topic_ref is not None else {}), - **({"group_human_message": group_human_message} if group_ref is not None or group_human_message else {}), - }) - # Presentation may need the name from this exact verified read. Keep it - # outside the persisted context and opt-in; it is never a cached grant - # or a substitute for the next admission/delivery owner's fresh check. - return {**selected, "observation": observation} if include_observation else selected - - def _resolve_observed(self, current: dict[str, Any], row: dict[str, Any], - observation: dict[str, Any], source: dict[str, Any]) -> dict[str, Any]: - return self._core("collaboration.conversation.bound_context", { - "current": current, "binding_id": row["binding_id"], "observation": observation, - "available_projects": self.projects.available(), **source, - **({"available_goal_ids": self.goal_scope_ids(row)} if row.get("goal_scope") == "all_registered" else {}), - }) + return build_resolved_binding( + current=current, + row=row, + observation=observation, + resolve_observed_fn=self._resolve_observed, + source_ref=source_ref, + sender_ref=sender_ref, + private_human_message=private_human_message, + session_context=session_context, + group_ref=group_ref, + topic_ref=topic_ref, + group_human_message=group_human_message, + include_observation=include_observation, + origin=origin, + session=session, + ) + + def _resolve_observed( + self, + current: BindingPayloadView, + row: BindingPayloadView, + observation: BindingPayloadView, + source: BindingPayloadView, + ) -> BindingPayload: + projects = self._require_projects() + return self._core( + "collaboration.conversation.bound_context", + { + "current": current, + "binding_id": row["binding_id"], + "observation": observation, + "available_projects": projects.available(), + **source, + **( + {"available_goal_ids": self.goal_scope_ids(row)} + if row.get("goal_scope") == "all_registered" + else {} + ), + }, + ) + + def _resolve_source_mapping( + self, + *, + binding_id: str, + source: BindingPayloadView, + include_observation: bool = False, + session: BindingPayloadView | None = None, + origin: str | None = None, + ) -> ResolvedBindingDict: + raw_session_ctx = source.get("session_context") + session_context = raw_session_ctx if isinstance(raw_session_ctx, Mapping) else None + raw_group_ref = source.get("group_ref") + group_ref = str(raw_group_ref) if raw_group_ref is not None else None + raw_topic_ref = source.get("topic_ref") + topic_ref = str(raw_topic_ref) if raw_topic_ref is not None else None + raw_origin = source.get("origin") + resolved_origin = ( + origin + if origin is not None + else (str(raw_origin) if raw_origin is not None else None) + ) + return self.resolve( + binding_id=binding_id, + source_ref=str(source["source_ref"]), + sender_ref=str(source["sender_ref"]), + private_human_message=bool(source["private_human_message"]), + session_context=session_context, + group_ref=group_ref, + topic_ref=topic_ref, + group_human_message=bool(source.get("group_human_message", False)), + include_observation=bool( + source.get("include_observation", include_observation) + ), + origin=resolved_origin, + session=session, + ) @contextmanager - def input_context(self, saved: dict[str, Any], *, origin: str, session: dict[str, Any], - store: ChatSessionStore) -> Iterator[dict[str, Any]]: - """Observe outside the publication fence, then retain it through enqueue. - - Saved fields select an identity; fresh Core checks grant it. Local Web - continuation keeps its actual origin and never becomes a provider event. - """ - if origin == "web": - source = {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": False, "origin": "web", "session_context": saved, - **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})} - elif origin in {"lark", "external"}: - source = self._session_source(saved) - else: - raise ValueError("unsupported bound conversation input origin") - observed = self.resolve(binding_id=saved["binding_id"], include_observation=True, session=session, **source) - with exclusive_file_lock(self.path, operation="admit_bound_input"): - current = self.read() - if next((row for row in current.get("bindings", []) - if row.get("binding_id") == saved["binding_id"]), None) != observed["binding"]: - raise ValueError("conversation binding changed before input admission") - # The provider observation may have waited. Re-read canonical - # identity under the binding fence before Core authorizes input. - fresh = store.load_session(session["session_id"]) - if fresh is None: - raise KeyError("chat session was not found") - yield self._resolve_observed(current, observed["binding"], observed["observation"], - {**source, "session": self._session_observation(fresh)}) - - @staticmethod - def _session_observation(session: dict[str, Any]) -> dict[str, Any]: - return {key: session.get(key) for key in ( - "session_id", "goal_id", "agent_id", "executor_endpoint_id", "channel_id", - "session_mode", "status", "project_context", "steward_context", - "manager_executor_allocation", "upstream_context_history")} - - def local_sessions(self, binding_id: str, *, app_steward_entry: bool = False) -> list[dict[str, Any]]: - return self.local_session_snapshot(binding_id, app_steward_entry=app_steward_entry)["sessions"] - - def local_session_snapshot(self, binding_id: str, *, app_steward_entry: bool = False) -> dict[str, Any]: - current, sessions, source = self._observe_local_sessions(binding_id, app_steward_entry=app_steward_entry) - payload = {"sessions": [self.controller.store.public_session(session) for session in sessions], - "conversation_source": source} + def input_context( + self, + saved: BindingPayloadView, + *, + origin: str, + session: BindingPayloadView, + store: BindingSessionStoreProtocol, + ) -> Iterator[BindingPayload]: + """Observe outside the publication fence, then retain it through enqueue.""" + with input_context_flow( + bindings_path=self.path, + saved=saved, + origin=origin, + session=session, + store=store, + session_source_fn=self._session_source, + resolve_source_fn=self._resolve_source_mapping, + read_fn=self.read, + resolve_observed_fn=self._resolve_observed, + lock_fn=exclusive_file_lock, + ) as resolved: + yield resolved + + _session_observation = staticmethod(session_observation) + + def local_sessions( + self, binding_id: str, *, app_steward_entry: bool = False + ) -> list[BindingPayload]: + return self.local_session_snapshot( + binding_id, app_steward_entry=app_steward_entry + )["sessions"] + + def local_session_snapshot( + self, binding_id: str, *, app_steward_entry: bool = False + ) -> LocalSessionSnapshotDict: + if self.controller is None: + raise ValueError("the bound conversation store is unavailable") + current, sessions, source = self._observe_local_sessions( + binding_id, app_steward_entry=app_steward_entry + ) + payload = LocalSessionSnapshotDict( + { + "sessions": [ + self.controller.store.public_session(session) for session in sessions + ], + "conversation_source": source, + } + ) self._recheck_local_bindings(current) return payload - def _recheck_local_bindings(self, observed: dict[str, Any]) -> None: + def _recheck_local_bindings(self, observed: BindingPayloadView) -> None: if self.read() != observed: raise ValueError("conversation binding changed during discovery") def _observe_local_sessions( - self, binding_id: str, *, app_steward_entry: bool, - ) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]: - """Read original targets; metadata hints never replace Core's grant. - - This read-only snapshot does not wait for a mutation fence. Core checks - the observed grant, and a final canonical read rejects concurrent grant - changes. Discovery neither restores a thread nor creates work; actual - submissions retain their fresh identity and effect-time grant fences. - """ - if self.controller is None: - raise ValueError("the bound conversation store is unavailable") - row = next((item for item in self.read()["bindings"] if item["binding_id"] == binding_id), None) - if row is None: - raise ValueError("conversation binding is no longer authorized") - observation = dict(self.observe(row["transport_ref"])) - store = self.controller.store - - def mentions_binding(session: dict[str, Any]) -> bool: - return any(isinstance(session.get(key), dict) and session[key].get("binding_id") == binding_id - for key in ("project_context", "steward_context")) - - # Keep aliases in the candidate set even when their own metadata is - # unrelated. Core must still see duplicate canonical Session identities. - hints = (session for path, session in store.iter_session_metadata() - if path.parent.name != session["session_id"] or mentions_binding(session)) - sessions: list[dict[str, Any]] = [] - for hint in sorted(hints, key=lambda item: str(item.get("updated_at") or ""), reverse=True): - session = store.load_session(hint["session_id"]) - if session and mentions_binding(session): - sessions.append(session) - current = self.read() - if next((item for item in current["bindings"] if item["binding_id"] == binding_id), None) != row: - raise ValueError("conversation binding changed during identity verification") - projects = self.projects.available() - result = self._core("collaboration.conversation.local_sessions", { - "current": current, "binding_id": binding_id, "observation": observation, - "available_projects": projects, - "sessions": [self._session_observation(session) for session in sessions], - **({"app_steward_entry": True} if app_steward_entry else {}), - **({"available_goal_ids": self.goal_scope_ids(row)} if row.get("goal_scope") == "all_registered" else {}), - }) - # Build the lookup only after Core has rejected duplicate identity; - # an IO dictionary must not silently turn ambiguity into one target. - by_id = {session["session_id"]: session for session in sessions} - project = next(project for project in projects if project["project_ref"] == row["project_ref"]) - source = {"binding_id": binding_id, "app_ref": row["transport_ref"], - "context_kind": row["context_kind"], "audience": row.get("audience", "owner"), - "project_title": Path(project["workspace_path"]).name, "context_available": True, - "executor_endpoint_id": row["executor_endpoint_id"]} - # Bind the projection to the exact atomic configuration Core checked. - # This is not an execution grant or a cached provider observation. - return current, [by_id[sid] for sid in result["session_ids"]], source - - def goal_scope_ids(self, binding: dict[str, Any]) -> list[str]: - if binding.get("goal_scope") != "all_registered": - return list(binding.get("goal_ids", [])) - from ...control_plane.projects.registry_codec import load_registry - if self.controller is None or self.controller.registry_path is None: - raise ValueError("the steward registry is unavailable") - return [goal["id"] for goal in load_registry(self.controller.registry_path).get("goals", [])] - - def delivery_channels(self, binding: dict[str, Any]) -> list[str]: - if self.controller is None: - return [] - from ..manager_context import POLICY_SCHEMA, _root - path = _root(self.controller.coordination_runtime_root) / "policy.json" - if not path.exists(): - return [] - policy = _read_json(path) - if policy.get("schema_version") != POLICY_SCHEMA or not isinstance(policy.get("sources"), dict): - raise ValueError("invalid manager policy") - prefix = f"manager.external.native.{binding['binding_id']}." - return [channel for channel, source in policy["sources"].items() - if channel.startswith(prefix) and isinstance(source, dict) - and binding["operator_ref"] in source.get("sender_ids", [])] - - def ensure_delivery_scope(self, selected: dict[str, Any], *, if_absent: bool = True, execute: bool = True) -> None: - if selected["binding"].get("goal_scope") not in {"all_registered", "selected"} or self.controller is None: - return - # Match configuration's binding -> source-policy order. An observation - # from before disconnect must never recreate its retired source grant. - with exclusive_file_lock(self.path, operation="configure_bound_delivery_scope"): - if selected["binding"] not in self.read()["bindings"]: - raise ValueError("conversation binding is no longer authorized") - self._ensure_delivery_scope(selected, if_absent=if_absent, execute=execute) - - def _ensure_delivery_scope(self, selected: dict[str, Any], *, if_absent: bool = True, execute: bool = True) -> None: + self, binding_id: str, *, app_steward_entry: bool + ) -> tuple[BindingStateDict, list[BindingPayload], BindingPayload]: + """Read original targets; metadata hints never replace Core's grant.""" + return observe_local_sessions_flow( + binding_id=binding_id, + app_steward_entry=app_steward_entry, + controller=self.controller, + projects=self.projects, + read_fn=self.read, + observe_fn=self.observe, + core_fn=self._core, + goal_scope_ids_fn=self.goal_scope_ids, + ) + + def goal_scope_ids(self, binding: BindingPayloadView) -> list[str]: + return goal_scope_ids_flow(self.controller, binding) + + def delivery_channels(self, binding: BindingPayloadView) -> list[str]: + return delivery_channels_flow( + self.controller, binding, read_json_fn=_read_json + ) + + def ensure_delivery_scope( + self, + selected: BindingPayloadView, + *, + if_absent: bool = True, + execute: bool = True, + ) -> None: + ensure_delivery_scope_flow( + bindings_path=self.path, + controller=self.controller, + selected=selected, + if_absent=if_absent, + execute=execute, + read_fn=self.read, + inner_ensure_fn=self._ensure_delivery_scope, + lock_fn=exclusive_file_lock, + ) + + def _ensure_delivery_scope( + self, + selected: BindingPayloadView, + *, + if_absent: bool = True, + execute: bool = True, + ) -> None: """The caller retains the binding publication fence, including configure.""" - binding = selected["binding"] - if binding.get("goal_scope") not in {"all_registered", "selected"} or self.controller is None: - return - from ..manager_context import configure_delivery_scope - configure_delivery_scope(self.controller.coordination_runtime_root, - channel=selected["channel_id"], local_delivery_scope=binding["goal_scope"], - sender_id=binding["operator_ref"], execute=execute, if_absent=if_absent) - - @staticmethod - def _session_source(saved: dict[str, Any]) -> dict[str, Any]: - if saved.get("audience") == "bound_group": - return {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": False, "group_ref": saved["group_ref"], - "topic_ref": saved["topic_ref"], "group_human_message": True, "session_context": saved} - return {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"], - "private_human_message": True, "session_context": saved, - **({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})} - - def session_context(self, saved: dict[str, Any], *, session: dict[str, Any] | None = None) -> dict[str, Any]: - return self.resolve(binding_id=saved["binding_id"], session=session, **self._session_source(saved)) - - def manager_runtime_owner(self, saved: dict[str, Any], channel_id: str) -> bool: + apply_delivery_scope_flow( + self.controller, selected, if_absent=if_absent, execute=execute + ) + + _session_source = staticmethod(session_source) + + def session_context( + self, + saved: BindingPayloadView, + *, + session: BindingPayloadView | None = None, + ) -> ResolvedBindingDict: + return self._resolve_source_mapping( + binding_id=str(saved["binding_id"]), + source=self._session_source(saved), + session=session, + ) + + def manager_runtime_owner( + self, saved: BindingPayloadView, channel_id: str + ) -> bool: """Fresh Core audience proof; saved Session text is never authority.""" selected = self.session_context(saved) if selected["channel_id"] != channel_id: raise ValueError("bound manager audience changed") return selected["owner_manager_audience"] is True - def steward_scope(self, session: dict[str, Any]) -> list[str] | None: + def steward_scope(self, session: BindingPayloadView) -> list[str] | None: saved = session.get("steward_context") if not isinstance(saved, dict): return None selected = self.session_context(saved) - if session.get("goal_id") != "loopx-manager" or session.get("channel_id") != selected["channel_id"]: + if ( + session.get("goal_id") != "loopx-manager" + or session.get("channel_id") != selected["channel_id"] + ): raise ValueError("bound steward audience changed") - return list(selected["context"]["goal_ids"]) - - def adopt_created_goal(self, *, binding_id: str, source: dict[str, Any], proposal: dict[str, Any], - goal: dict[str, Any]) -> None: - selected = self.resolve(binding_id=binding_id, **source) - with exclusive_file_lock(self.path, operation="adopt_steward_created_goal"): - current = self.read() - result = self._core("collaboration.conversation.binding", { - "current": current, "expected_revision": current["revision"], "operation": "adopt_created_goal", - "binding_id": binding_id, "context": selected["context"], "proposal": proposal, - "goal": {"goal_id": goal["id"], "workspace_path": str(Path(goal["repo"]).resolve()), - "creation_operation_id": goal.get("creation_operation_id")}, - }) - if result["changed"]: - _atomic_write_json(self.path, result["state"]) - if self.read() != result["state"]: - raise OSError("steward scope publication did not verify") - - def agent_observation(self, session_id: str) -> dict[str, Any]: - """Read only the explicitly selected canonical attached Session/Goal. - - No host history, remote thread database or prior identity is discovered. - """ - from ...attached_session import require_current_attached_session, _require_bound_host - from ...control_plane.projects.registry_codec import load_registry - from ...registry import find_registry_goal - if self.controller is None or self.controller.registry_path is None: - raise ValueError("the attached Session registry is unavailable") - session = require_current_attached_session(store=self.controller.store, - registry_path=self.controller.registry_path, session_id=session_id) - registry = load_registry(self.controller.registry_path) - goal = find_registry_goal(registry, str(session.get("goal_id") or "")) - if goal is None or not goal.get("repo"): - raise ValueError("the exact Agent workspace is unavailable") - _require_bound_host(goal=goal, agent_id=session["agent_id"], host_surface=session["host_surface"], - host_session_id=session["upstream_thread_id"]) - return {"session": {key: session.get(key) for key in ["session_id", "goal_id", "goal_instance_id", - "agent_id", "executor_endpoint_id", "session_mode", "status", "external_conversation_binding_id"]}, - "goal": {"goal_id": goal["id"], "workspace_path": str(Path(goal["repo"]).resolve()), - "registered_agents": (goal.get("coordination") or {}).get("registered_agents", [])}, - "host_binding_verified": True, "host_ref": _host_ref(session), - "host_audience_binding_ids": _host_audiences(self.controller.store, session)} - - def agent_candidates(self, binding_id: str) -> list[dict[str, Any]]: - row = next(item for item in self.read()["bindings"] if item["binding_id"] == binding_id) - if row["context_kind"] != "project" or row.get("audience") == "group" or self.controller is None: - return [] - project = next((item for item in self.projects.available() if item["project_ref"] == row["project_ref"]), None) - if project is None: - return [] - candidates = [] - for session in self.controller.store.list_sessions(): - if session.get("session_mode") != "attached_host" or session.get("status") == "closed": - continue - try: - observed = self.agent_observation(session["session_id"]) - if (observed["session"]["status"] in {"ready", "busy"} - and observed["goal"]["workspace_path"] == project["workspace_path"] - and observed["session"].get("external_conversation_binding_id") in {None, binding_id} - and all(owner == binding_id for owner in observed["host_audience_binding_ids"])): - candidates.append(observed["session"]) - except (ValueError, OSError, KeyError): - continue - return candidates[:16] - - def change_agent_target(self, *, binding_id: str, expected_revision: int, - session_id: str | None = None, target_ref: str | None = None) -> dict[str, Any]: - row = next((item for item in self.read()["bindings"] if item["binding_id"] == binding_id), None) - if row is None: - raise ValueError("conversation binding is no longer authorized") - # Provider IO must not prevent disconnect from publishing revocation. - # Recheck the exact binding under its fence before using this observation. - observation = self.observe(row["transport_ref"]) - with exclusive_file_lock(self.path, operation="configure_conversation_agent_target"): - current = self.read() - if next((item for item in current["bindings"] if item["binding_id"] == binding_id), None) != row: - raise ValueError("conversation binding changed during identity verification") - params = {"current": current, "expected_revision": expected_revision, "binding_id": binding_id, - "observation": observation, "available_projects": self.projects.available()} - if session_id is not None: - observed = self.agent_observation(session_id) - target = {key: observed["session"].get(key) for key in ["session_id", "goal_id", "goal_instance_id", - "agent_id", "executor_endpoint_id"]} - params.update(operation="grant_agent_target", target={"target_ref": uuid.uuid4().hex[:24], "host_ref": observed["host_ref"], **target}, - target_observation=observed) - else: - params.update(operation="revoke_agent_target", target_ref=target_ref) - result = self._core("collaboration.conversation.binding", params) - if result["changed"]: - if session_id is not None: - # agent_observation already requires this exact local controller. - assert self.controller is not None - self.controller.store.update_session(session_id, external_conversation_binding_id=binding_id) - _atomic_write_json(self.path, result["state"]) - if self.read() != result["state"]: - raise OSError("Agent target grant publication did not verify") - state: dict[str, Any] = result["state"] - return state - - def resolve_agent_target(self, selected: dict[str, Any], target: dict[str, Any]) -> dict[str, Any]: - return self._core("collaboration.conversation.agent_target", {"binding": selected["binding"], - "context": selected["context"], "target": target, - "target_observation": self.agent_observation(target["session_id"])}) - + raw_goal_ids = selected["context"]["goal_ids"] + return ( + [str(item) for item in raw_goal_ids] + if isinstance(raw_goal_ids, list) + else [] + ) + + def adopt_created_goal( + self, + *, + binding_id: str, + source: BindingPayloadView, + proposal: BindingPayloadView, + goal: BindingPayloadView, + ) -> None: + adopt_created_goal_flow( + bindings_path=self.path, + binding_id=binding_id, + source=source, + proposal=proposal, + goal=goal, + resolve_source_fn=lambda bid, src: self._resolve_source_mapping( + binding_id=bid, source=src + ), + read_fn=self.read, + core_fn=self._core, + write_json_fn=_atomic_write_json, + lock_fn=exclusive_file_lock, + ) + + def agent_observation(self, session_id: str) -> BindingPayload: + """Read only the explicitly selected canonical attached Session/Goal.""" + return agent_observation_flow(self.controller, session_id) + + def agent_candidates(self, binding_id: str) -> list[BindingPayload]: + return agent_candidates_flow( + binding_id=binding_id, + controller=self.controller, + projects=self.projects, + read_fn=self.read, + observe_agent_fn=self.agent_observation, + ) + + def change_agent_target( + self, + *, + binding_id: str, + expected_revision: int, + session_id: str | None = None, + target_ref: str | None = None, + ) -> BindingStateDict: + return change_agent_target_flow( + bindings_path=self.path, + binding_id=binding_id, + expected_revision=expected_revision, + session_id=session_id, + target_ref=target_ref, + controller=self.controller, + projects=self.projects, + read_fn=self.read, + observe_fn=self.observe, + observe_agent_fn=self.agent_observation, + core_fn=self._core, + write_json_fn=_atomic_write_json, + lock_fn=exclusive_file_lock, + ) + + def resolve_agent_target( + self, selected: BindingPayloadView, target: BindingPayloadView + ) -> BindingPayload: + return self._core( + "collaboration.conversation.agent_target", + { + "binding": selected["binding"], + "context": selected["context"], + "target": target, + "target_observation": self.agent_observation(str(target["session_id"])), + }, + ) @effect_runtime_request_scope() - def stop_recoveries(self, current: dict[str, Any]) -> list[dict[str, Any]]: - """Project revoked execution from canonical Turns, never recreate a grant. - - Session and external-target context retain the exact binding identity - across restart. No second stop ledger or provider diagnostics are needed. - A recovery disappears only when the existing Turn owner settles it. - Share the runtime source observation, while reading each queue afresh. - """ - if self.controller is None: - return [] - authorized = {row["binding_id"] for row in current["bindings"]} - store = self.controller.store - pending: dict[str, dict[str, Any]] = {} - for row in store.list_sessions(): - session = store.load_session(row["session_id"]) - if session is None: - continue - turns = store.queued_turns(session["session_id"]) - active = store.load_turn(session["session_id"], session["active_turn_id"]) if session.get("active_turn_id") else None - if active: - turns.append(active) - for turn in turns: - if turn.get("status") in TERMINAL_TURN_STATES: - continue - target = turn.get("external_agent_target") or {} - context = target.get("context") or session.get("project_context") or session.get("steward_context") or {} - binding_id = context.get("binding_id") - if not binding_id or binding_id in authorized: - continue - recovery = pending.setdefault(binding_id, {"binding_id": binding_id, - "project_ref": context.get("project_ref", ""), "pending_count": 0}) - recovery["pending_count"] += 1 - return [pending[key] for key in sorted(pending)] - - -def validate_external_agent_turn(*, store: Any, session: dict[str, Any], - goal: dict[str, Any] | None, turn: dict[str, Any]) -> None: - """Called under the grant and canonical queue fences before host claim. - - The owner-local grant persists independently of a live provider connection. - Admission and result delivery also verify the App/owner with the provider. - """ - saved = turn.get("external_agent_target") - if saved is None: - return - from ...attached_session import _require_bound_host - if not isinstance(saved, dict) or turn.get("origin") not in {"lark", "external"} or goal is None: - raise ValueError("the attached external audience is unavailable") - context, target = saved["context"], saved["target"] - if not Path(goal["repo"]).is_dir(): - raise ValueError("the attached Agent workspace is unavailable") - state = _read_json(store.root / "conversation-bindings.json") - selected = next((row for row in state["bindings"] if row["binding_id"] == context["binding_id"]), None) - if selected is None: - raise ValueError("the Agent audience grant was revoked") - _require_bound_host(goal=goal, agent_id=session["agent_id"], host_surface=session["host_surface"], - host_session_id=session["upstream_thread_id"]) - ChatConversationBindings._core("collaboration.conversation.agent_target", {"binding": selected, - "context": context, "target": target, "target_observation": {"session": session, - "goal": {"goal_id": goal["id"], "workspace_path": str(Path(goal["repo"]).resolve()), - "registered_agents": (goal.get("coordination") or {}).get("registered_agents", [])}, - "host_binding_verified": True, "host_ref": _host_ref(session), - "host_audience_binding_ids": _host_audiences(store, session)}}) - - -def _host_ref(session: dict[str, Any]) -> str: - return hashlib.sha256(f"{session['host_surface']}\0{session['upstream_thread_id']}".encode()).hexdigest()[:24] - - -def _host_audiences(store: Any, session: dict[str, Any]) -> list[str]: - """Content-free stamps in this canonical store, including closed Sessions.""" - owners = set() - for row in store.list_sessions(): - candidate = store.load_session(row["session_id"]) - if (candidate and candidate.get("host_surface") == session["host_surface"] - and candidate.get("upstream_thread_id") == session["upstream_thread_id"] - and candidate.get("external_conversation_binding_id")): - owners.add(candidate["external_conversation_binding_id"]) - return sorted(owners) - - -class OriginalConversationRequests: - """Chat/source/store IO for the shared original-conversation request profile. - - The existing source policy, peer operation, request, revision, result and - Session FIFO remain their respective owners. No shadow queue is created. - """ - - def __init__(self, controller): - self.controller = controller - self.store = controller.store - self.root = controller.coordination_runtime_root - self.bindings = controller.project_contexts.conversation_bindings - if self.bindings is None: - raise ValueError("original conversation bindings are unavailable") - - _core = staticmethod(ChatConversationBindings._core) - - def _policy(self): - from ...control_plane.collaboration.inbox import _read, _root - path = _root(self.root) / "policy.json" - return _read(path) if path.exists() else {"schema_version": "loopx_manager_context_policy_v1", "sources": {}} - - def _observation(self, session_id): - session = self.store.load_session(session_id) - if session is None: - raise ValueError("original project Session is unavailable") - saved = session.get("project_context") or {} - current = self.bindings.read() - binding = next((row for row in current["bindings"] if row["binding_id"] == saved.get("binding_id")), None) - if binding is None: - raise ValueError("original conversation grant was revoked") - observed = dict(self.bindings.observe(binding["transport_ref"])) - return binding, observed - - def _recipient(self, session_id, expected_binding, observation, policy): - current = self.bindings.read() - if next((row for row in current["bindings"] if row["binding_id"] == expected_binding["binding_id"]), None) != expected_binding: - raise ValueError("original conversation binding changed during verification") - return self._core("collaboration.project.recipient", {"current": current, - "binding_id": expected_binding["binding_id"], "observation": observation, - "available_projects": self.bindings.projects.available(), - "session": self.store.load_session(session_id), "policy": policy, - "sessions": [self.store.load_session(row["session_id"]) for row in self.store.list_sessions()]}) - - @contextmanager - def _source(self, requester, parent_request_id, *, require_active=True): - from ...control_plane.collaboration.goal_instance_scope import collaboration_goal_scope - from ...control_plane.collaboration.inbox import _entry - from ...control_plane.collaboration.peer_context_observation import require_parent_context_access - ref = requester.get("goal_ref") or {} - with collaboration_goal_scope(self.controller.registry_path, goal_id=ref.get("goal_id"), - agents=(requester.get("agent_id"),), caller_goal_ref=ref, require_active=require_active) as scope: - if not scope.exact or requester != {"goal_ref": scope.caller_goal_ref, "agent_id": requester.get("agent_id")}: - raise ValueError("an exact original requester is required") - parent = _entry(self.root, scope.goal_id, requester["agent_id"], parent_request_id, scope=scope) - if "request_control" in parent and self._view(parent)["control_state"] in {"cancelled", "cancellation_pending"}: - raise ValueError("the original source request was cancelled") - access = require_parent_context_access(self.root, self.controller.registry_path, parent, - requester["agent_id"], scope=scope) - yield {"requester": requester, "parent": parent, "parent_request_id": parent_request_id, - "original_source_id": access["source_id"], "parent_access_verified": True}, scope - - @contextmanager - def _fenced(self, session_id, requester, parent_request_id): - from ...control_plane.collaboration.source_policy_fence import source_policy_fence - from ...control_plane.collaboration.inbox import _root - binding, observed = self._observation(session_id) - # Every writer uses source -> Goal -> binding -> request -> Session. - # Provider IO precedes these fences; canonical identity is reread inside. - with source_policy_fence(_root(self.root) / "policy.json"), self._source(requester, parent_request_id) as (source, scope): - with exclusive_file_lock(self.bindings.path, operation="original_conversation_peer"): - policy = self._policy() - selected = self._recipient(session_id, binding, observed, policy) - yield {**source, "policy": policy, "recipient": selected["recipient"], - "current_recipient": selected["recipient"], "policy_sha256": selected["policy_sha256"]}, scope - - def configure(self, session_id, body): - from ...control_plane.collaboration.inbox import _root, _write, _read - from ...control_plane.collaboration.source_policy_fence import source_policy_fence - enable = body.get("grant") - if not isinstance(enable, bool): - raise ValueError("grant must be an explicit boolean") - - def apply(facts): - plan = self._core("collaboration.source.original_conversation_grant", { - **facts, "grant": enable, "expected_policy_sha256": body.get("expected_policy_sha256")}) - path = _root(self.root) / "policy.json" - if body.get("execute") is True and plan["would_change"]: - _write(path, plan["policy"]) - if _read(path) != plan["policy"]: - raise OSError("original conversation source grant did not verify") - return {"ok": True, "executed": body.get("execute") is True, - **{key: value for key, value in plan.items() if key != "policy"}} - - if enable: - with self._fenced(session_id, body["requester"], body["parent_request_id"]) as (facts, _): - return apply(facts) - # An owner may revoke a retained grant even while its provider or source - # is unavailable. - with source_policy_fence(_root(self.root) / "policy.json"): - recipient = body["recipient"] - if recipient.get("session_id") != session_id: - raise ValueError("original conversation revocation scope mismatch") - return apply({"policy": self._policy(), "recipient": recipient, - "requester": body["requester"], "parent_request_id": body["parent_request_id"], - "original_source_id": body["source_id"]}) - - def management_view(self, session_id, *, search="", cursor=None): - from ...control_plane.collaboration.inbox import _root, _read - from ...control_plane.collaboration.source_policy_fence import source_policy_fence - with source_policy_fence(_root(self.root) / "policy.json"): - policy = self._policy() - view = self._core("collaboration.source.original_conversation_grants", {"policy": policy, "session_id": session_id}) - for grant in view["grants"]: - requester = grant["requester"] - address = {"goal_ref": requester["goal_ref"], "agent_id": requester["agent_id"]} - try: - from ...control_plane.collaboration.inbox import _hash - parent = _read(_root(self.root) / "entries" / _hash(address) / (grant["parent_request_id"] + ".json")) - if parent.get("goal_ref") != requester["goal_ref"] or parent.get("agent_id") != requester["agent_id"]: - raise ValueError("source grant parent identity changed") - grant["source_purpose"] = (parent.get("brief") or {}).get("purpose", parent.get("message", "")) - except (ValueError, OSError): - grant["source_purpose"] = None - try: - binding, observed = self._observation(session_id) - with exclusive_file_lock(self.bindings.path, operation="original_conversation_inventory"): - view.update(self._recipient(session_id, binding, observed, policy), available=True) - except (ValueError, KeyError, OSError) as exc: - return {"ok": True, **view, "available": False, "error": str(exc), "candidates": [], "requests": []} - candidates, unreadable, overflow = [], 0, False - # Content is projected only to the trusted local owner. A later grant - # still rechecks the exact registration, parent lineage and source. - for path in sorted((_root(self.root) / "entries").glob("*/*.json")): - try: - row = _read(path) - if row.get("schema_version") != "loopx_manager_context_entry_v2" or not row.get("goal_ref"): - continue - purpose = (row.get("brief") or {}).get("purpose", row.get("message", "")) - if search.strip().casefold() not in " ".join((row["goal_ref"]["goal_id"], row["agent_id"], purpose)).casefold(): - continue - candidates.append({"requester": {"goal_ref": row["goal_ref"], "agent_id": row["agent_id"]}, - "parent_request_id": row["request_id"], "purpose": (row.get("brief") or {}).get("purpose", row.get("message", ""))}) - if len(candidates) == 128: - overflow = True - break - except (ValueError, OSError, KeyError): - unreadable += 1 - view.update(candidates=candidates, coverage={"unreadable": unreadable, "overflow": overflow}) - page = self._inbox(view["recipient"], mark_read=False, cursor=cursor) - view["requests"], view["requests_has_more"] = page["items"], page["has_more"] - view["requests_next_cursor"] = page["next_cursor"] - from ...control_plane.collaboration.inbox import result_paths, inspect_result_identity, reply_status - for item in view["requests"]: - results = [] - statuses = {row.get("result_key", row["phase"]): row["status"] for row in reply_status(self.root, item)} - queue = self._core("collaboration.project.continuation", {"entry": self._entry(item["request_id"], item["recipient"])}) - turn = self.store.turn_for_client(session_id, queue["client_turn_id"]) - item["queue_status"] = turn.get("status") if turn else None - for path in result_paths(_root(self.root) / "replies" / item["request_id"]): - reply = _read(path) - if inspect_result_identity(reply, self._entry(item["request_id"], item["recipient"]), path): - results.append({"result_key": path.stem, "text": reply["text"], "decision": reply["decision"], - "request_revision": reply.get("request_revision", 1), "delivery_status": statuses.get(path.stem, "queued")}) - item["returns"] = results - return {"ok": True, **view} - - def discover(self, requester, parent_request_id): - from ...control_plane.collaboration.inbox import _root - from ...control_plane.collaboration.source_policy_fence import source_policy_fence - with source_policy_fence(_root(self.root) / "policy.json"), self._source(requester, parent_request_id) as (source, _): - grants = self._core("collaboration.source.original_conversation_grants", {"policy": self._policy()})["grants"] - recipients, unavailable = [], 0 - for grant in grants: - if grant["requester"] != requester or grant["parent_request_id"] != parent_request_id: - continue - try: - with self._fenced(grant["recipient"]["session_id"], requester, parent_request_id) as (facts, _): - self._core("collaboration.source.original_conversation_access", facts) - if facts["recipient"] != grant["recipient"]: - raise ValueError("original conversation recipient changed") - session = self.store.load_session(facts["recipient"]["session_id"]) - recipients.append({"recipient": facts["recipient"], "title": session.get("title") or "Project conversation"}) - except (ValueError, KeyError, OSError): - unavailable += 1 - return {"ok": True, "recipients": recipients, "unavailable": unavailable} - - def publish(self, body): - from ...control_plane.collaboration.inbox import _hash, _now, _read, _request_lock, _root, _write - from ...control_plane.collaboration.peers import _operation_address - recipient = body["recipient"] - session_id = recipient["session_id"] - with self._fenced(session_id, body["requester"], body["parent_request_id"]) as (facts, scope): - if recipient != facts["recipient"]: - raise ValueError("original conversation recipient identity changed") - source_id, op_path = _operation_address(self.root, scope, body["requester"]["agent_id"], body["operation_id"]) - # Native planning owns identity and replay. The old operation is - # consulted before any queue input or return route can be written. - prior = _read(op_path) if op_path.exists() else None - preview = self._core("collaboration.project.request", {**facts, "source_id": source_id, - "request": {"recipient": recipient, "brief": body["brief"]}, "observed_at": _now()}) - request_id = preview["entry"]["request_id"] - path = _root(self.root) / "entries" / _hash({"recipient": recipient}) / (request_id + ".json") - with _request_lock(self.root, request_id, None, op_path, force_exact=True): - prior = _read(op_path) if op_path.exists() else prior - plan = self._core("collaboration.project.request", {**facts, "source_id": source_id, - "request": {"recipient": recipient, "brief": body["brief"]}, "observed_at": _now(), - "operation": prior, "entry": _read(path) if path.exists() else None}) - row = plan["entry"] - route = plan["return_route"] - route_path = _root(self.root) / "roundtrips" / (request_id + ".json") - if route_path.exists() and _read(route_path) != route: - raise ValueError("original requester return route identity conflict") - if prior is None: - _write(op_path, plan["operation"]) - if not route_path.exists(): - _write(route_path, route) - if _read(route_path) != route: - raise OSError("original requester return route did not verify") - if not plan["replayed"]: - _write(path, row) - if _read(path) != row: - raise OSError("original conversation request did not verify") - view = self._view(row) - if view["control_state"] == "cancelled": - raise ValueError("original conversation request is cancelled") - turn, created = self._enqueue(row) - recovered = self._resume(session_id, turn, created) - return {"ok": True, "request_id": request_id, "recipient": recipient, "turn_id": turn["turn_id"], - "status": turn["status"], "replayed": not created, "goal_created": False, "recovered_result": recovered} - - def _enqueue(self, row): - queue = self._core("collaboration.project.continuation", {"entry": row}) - turn, created = self.store.create_queued_turn(row["recipient"]["session_id"], - client_turn_id=queue["client_turn_id"], message=queue["message"], origin="peer", - collaboration_request=queue["collaboration_request"]) - return turn, created - - def _stop_turns(self, session_id, client_ids): - stopped = None - for client_id in client_ids: - turn = self.store.turn_for_client(session_id, client_id) - if turn and turn["status"] not in TERMINAL_TURN_STATES: - stopped = self.controller.interrupt_turn(session_id=session_id, turn_id=turn["turn_id"]) - return stopped - - def _resume(self, session_id, turn, created): - recovered = None - if not created and turn.get("collaboration_answer") is not None: - recovered = self._complete_answer(session_id, turn, turn["collaboration_answer"])["collaboration_result"] - if turn["status"] not in TERMINAL_TURN_STATES: - context = self.controller.project_contexts.session_context(self.store.load_session(session_id)) - self.controller.resume_session_queue(session_id=session_id, work_dir=Path(context["project"]), objective=str(context.get("objective") or context["title"])) - return recovered - - def _entry(self, request_id, recipient): - from ...control_plane.collaboration.inbox import _entry - return _entry(self.root, None, None, request_id, recipient=recipient) - - def _view(self, row): - return self._core("collaboration.request.control", {"entry": row, "input": {"operation": "inspect"}, "source": {}})["view"] - - def _inbox(self, recipient, *, mark_read, request_id=None, cursor=None): - from ...control_plane.collaboration.inbox import _now - result = self._core("collaboration.inbox.read", {"runtime_root": str(self.root.resolve()), - "scope": {"profile_id": "original_conversation_v0", "recipient": recipient}, - "operation": "receiver_read" if mark_read else "pending", "request_id": request_id, - "include_settled": not mark_read, - "cursor": cursor, - "observed_at": _now(), "read_command": "original project Turn supplied context"}, large_local_snapshot=True) - return result["result"] - - def control(self, body): - from ...control_plane.collaboration.goal_instance_scope import collaboration_goal_scope - from ...control_plane.collaboration.source_policy_fence import source_policy_fence - from ...control_plane.collaboration.inbox import _now, _root, _request_lock, _hash, _write, _read - requester, recipient = body["requester"], body["recipient"] - operation, parameters = body["control"], body["parameters"] - if operation not in {"inspect", "revise", "cancel"} or not isinstance(parameters, dict): - raise ValueError("unsupported original conversation source control") - row = self._entry(body["request_id"], recipient) - if row["requester"] != requester: - raise ValueError("original requester identity changed") - if operation == "revise": - fence = self._fenced(recipient["session_id"], requester, row["parent_request_id"]) - else: - # Revocation or a closed recipient must not remove the original - # source's ability to inspect/cancel its retained request. - @contextmanager - def retained_source(): - with source_policy_fence(_root(self.root) / "policy.json"), collaboration_goal_scope( - self.controller.registry_path, goal_id=requester["goal_ref"]["goal_id"], - agents=(requester["agent_id"],), caller_goal_ref=requester["goal_ref"]) as scope: - if not scope.exact: - raise ValueError("original requester exact instance is unavailable") - yield {}, scope - fence = retained_source() - with fence as (facts, _), _request_lock(self.root, row["request_id"], None, Path(), force_exact=True): - current = self._entry(row["request_id"], recipient) - route = _read(_root(self.root) / "roundtrips" / (row["request_id"] + ".json")) - self._core("collaboration.project.return_route", {"entry": current, "route": route}) - if operation == "revise": - if recipient != facts["recipient"]: - raise ValueError("original conversation recipient changed") - self._core("collaboration.source.original_conversation_access", facts) - plan = self._core("collaboration.request.control", {"entry": current, - "input": {**parameters, "operation": operation}, - "source": {"actor": "source", "actor_agent_id": requester["agent_id"], - "actor_requester": requester, - "recipient_active": operation == "revise", "observed_at": _now()}}) - if plan["changed"]: - _write(_root(self.root) / "entries" / _hash({"recipient": recipient}) / (row["request_id"] + ".json"), plan["entry"]) - if operation == "revise": - turn, created = self._enqueue(plan["entry"]) - stop = None - if operation == "revise": - self._resume(recipient["session_id"], turn, created) - elif operation == "cancel": - queue = self._core("collaboration.project.continuation", {"entry": plan["entry"]}) - stop = self._stop_turns(recipient["session_id"], [*queue["superseded_client_turn_ids"], queue["client_turn_id"]]) - return {"ok": True, "request_control": plan["view"], "replayed": plan.get("replayed", False), "turn_stop": stop} - - def validate_turn(self, session_id, turn): - if turn.get("origin") != "peer" and "collaboration_request" not in turn: - return - reference = turn.get("collaboration_request") - if turn.get("origin") != "peer" or not isinstance(reference, dict): - raise ValueError("peer Turn provenance is unavailable") - row = self._entry(reference["request_id"], reference["recipient"]) - if row["recipient"]["session_id"] != session_id: - raise ValueError("peer Turn does not belong to this original Session") - self._core("collaboration.project.continuation", {"entry": row, "turn": turn}) - with self._fenced(session_id, row["requester"], row["parent_request_id"]) as (facts, _): - self._validate_current(row, facts) - if self._view(row)["control_state"] == "cancelled": - raise ValueError("original conversation request was cancelled") - - def _validate_current(self, row, facts): - from ...control_plane.collaboration.inbox import _read, _root - self._core("collaboration.project.request", {**facts, "source_id": row["source_id"], - "request": {"recipient": row["recipient"], "brief": row["brief"]}, "entry": row, - "operation": None, "observed_at": row["delivered_at"], - "route": _read(_root(self.root) / "roundtrips" / (row["request_id"] + ".json"))}) - - def _complete_answer(self, session_id, turn, answer): - from ...control_plane.collaboration.inbox import _now, _request_lock, _root, _hash, _write, record_result - from ...chat import CHAT_AGENT_RESPONSE_SCHEMA_VERSION - if set(answer) != set(self._core("collaboration.project.response_schema", {})["required"]): - raise ValueError("original conversation answer has unsupported fields") - ref = turn["collaboration_request"] - row = self._entry(ref["request_id"], ref["recipient"]) - with self._fenced(session_id, row["requester"], row["parent_request_id"]) as (facts, _): - self._validate_current(row, facts) - self._core("collaboration.source.original_conversation_access", facts) - if facts["recipient"] != row["recipient"]: - raise ValueError("original conversation recipient changed") - with _request_lock(self.root, row["request_id"], None, Path(), force_exact=True): - row = self._entry(row["request_id"], row["recipient"]) - self._core("collaboration.project.continuation", {"entry": row, "turn": turn}) - view = self._view(row) - if (view["control_state"] == "cancelled" or answer["request_revision"] != view["revision"] - or answer["request_digest"] != view["revision_digest"]): - raise ValueError("original conversation answer belongs to a stale or cancelled request") - plan = self._core("collaboration.request.assess", {"entry": row, - "actor_recipient": row["recipient"], "recipient_active": True, "observed_at": _now(), - "revision": answer["request_revision"], "revision_digest": answer["request_digest"], - "decision": answer["decision"], "reason": answer["reason"]}) - if plan["changed"]: - _write(_root(self.root) / "entries" / _hash({"recipient": row["recipient"]}) / (row["request_id"] + ".json"), plan["entry"]) - receipt = record_result(self.root, row, "conclusion", answer["text"], request_revision=answer["request_revision"]) - return {"schema_version": CHAT_AGENT_RESPONSE_SCHEMA_VERSION, "message": answer["text"], - "proposals": [], "protected_action": None, "goal_draft": None, "context_handoff": None, - "gate": None, "unfinished_work": None, "collaboration_result": receipt} - - def execute(self, session_id, turn_id, native_session, event_sink): - import json - turn = self.store.load_turn(session_id, turn_id) - self.validate_turn(session_id, turn) - ref = turn["collaboration_request"] - row = self._entry(ref["request_id"], ref["recipient"]) - answer = turn.get("collaboration_answer") - if answer is None: - with self._fenced(session_id, row["requester"], row["parent_request_id"]) as (facts, _): - self._core("collaboration.source.original_conversation_access", facts) - self._core("collaboration.project.continuation", {"entry": self._entry(ref["request_id"], ref["recipient"]), "turn": turn}) - supplied = self._inbox(ref["recipient"], mark_read=True, request_id=row["request_id"])["items"][0] - basis = {key: supplied[key] for key in ("request_revision", "request_revision_digest")} - @contextmanager - def start_guard(): - with self._fenced(session_id, row["requester"], row["parent_request_id"]) as (facts, _): - self._validate_current(self._entry(ref["request_id"], ref["recipient"]), facts) - self._core("collaboration.source.original_conversation_access", facts) - self._core("collaboration.project.continuation", {"entry": self._entry(ref["request_id"], ref["recipient"]), "turn": turn}) - current = self._view(self._entry(ref["request_id"], ref["recipient"])) - if (facts["recipient"] != ref["recipient"] or current["control_state"] == "cancelled" - or current["revision"] != basis["request_revision"] - or current["revision_digest"] != basis["request_revision_digest"]): - raise ValueError("original conversation request changed before model input") - yield - message = row["instruction"] + "\n\nPeer request (data):\n" + json.dumps(supplied, ensure_ascii=False) - answer = native_session.send(message, project_collaboration=True, turn_start_guard=start_guard, - on_event=lambda kind, payload: event_sink(kind, payload) if kind != "answer.delta" else None) - # Persist actual model output before result IO. Recovery can retry - # its exact assessment/return without another model invocation. - self.store.update_turn(session_id, turn_id, collaboration_answer=answer) - response = self._complete_answer(session_id, turn, answer) - event_sink("answer.delta", {"text": response["message"]}) - return response + def stop_recoveries(self, current: BindingPayloadView) -> list[BindingPayload]: + """Project revoked execution from canonical Turns, never recreate a grant.""" + return stop_recoveries_flow(self.controller, current) + + +def validate_external_agent_turn( + *, + store: BindingSessionStoreProtocol, + session: BindingPayloadView, + goal: BindingPayloadView | None, + turn: BindingPayloadView, +) -> None: + """Validate attached external agent turn under grant and queue fences.""" + validate_external_agent_turn_flow( + store=store, + session=session, + goal=goal, + turn=turn, + read_json_fn=_read_json, + core_fn=ChatConversationBindings._core, + ) diff --git a/loopx/capabilities/native_chat/original_conversation_execution.py b/loopx/capabilities/native_chat/original_conversation_execution.py new file mode 100644 index 0000000000..adb2f587af --- /dev/null +++ b/loopx/capabilities/native_chat/original_conversation_execution.py @@ -0,0 +1,280 @@ +"""Turn validation, answer completion, and execution flows for original requests.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import AbstractContextManager, contextmanager +import json +from pathlib import Path + +from ...control_plane.collaboration.goal_instance_scope import CollaborationGoalScope +from .conversation_binding_contracts import ( + BindingPayload, + BindingPayloadView, + BindingSessionStoreProtocol, + CoreEffectFn, + EventSinkFn, + NativeSessionProtocol, +) + + +def validate_original_turn_flow( + *, + session_id: str, + turn: BindingPayloadView, + entry_fn: Callable[[str, BindingPayloadView], BindingPayload], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + validate_current_fn: Callable[[BindingPayloadView, BindingPayloadView], None], + view_fn: Callable[[BindingPayloadView], BindingPayload], + core_fn: CoreEffectFn, +) -> None: + if turn.get("origin") != "peer" and "collaboration_request" not in turn: + return + reference = turn.get("collaboration_request") + if turn.get("origin") != "peer" or not isinstance(reference, dict): + raise ValueError("peer Turn provenance is unavailable") + row = entry_fn(str(reference["request_id"]), reference["recipient"]) + row_recipient = row["recipient"] + if ( + not isinstance(row_recipient, Mapping) + or row_recipient.get("session_id") != session_id + ): + raise ValueError("peer Turn does not belong to this original Session") + core_fn("collaboration.project.continuation", {"entry": row, "turn": turn}) + requester = row["requester"] + assert isinstance(requester, Mapping) + with fenced_fn(session_id, requester, str(row["parent_request_id"])) as (facts, _): + validate_current_fn(row, facts) + if view_fn(row)["control_state"] == "cancelled": + raise ValueError("original conversation request was cancelled") + + +def validate_current_original_flow( + *, + root: Path, + row: BindingPayloadView, + facts: BindingPayloadView, + core_fn: CoreEffectFn, +) -> None: + from ...control_plane.collaboration.inbox import _read, _root + + core_fn( + "collaboration.project.request", + { + **facts, + "source_id": row["source_id"], + "request": {"recipient": row["recipient"], "brief": row["brief"]}, + "entry": row, + "operation": None, + "observed_at": row["delivered_at"], + "route": _read( + _root(root) / "roundtrips" / (str(row["request_id"]) + ".json") + ), + }, + ) + + +def complete_original_answer_flow( + *, + root: Path, + session_id: str, + turn: BindingPayloadView, + answer: BindingPayloadView, + entry_fn: Callable[[str, BindingPayloadView], BindingPayload], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + validate_current_fn: Callable[[BindingPayloadView, BindingPayloadView], None], + view_fn: Callable[[BindingPayloadView], BindingPayload], + core_fn: CoreEffectFn, +) -> BindingPayload: + from ...chat import CHAT_AGENT_RESPONSE_SCHEMA_VERSION + from ...control_plane.collaboration.inbox import ( + _hash, + _now, + _request_lock, + _root, + _write, + record_result, + ) + + required_fields = core_fn("collaboration.project.response_schema", {})["required"] + if not isinstance(required_fields, list) or set(answer) != set(required_fields): + raise ValueError("original conversation answer has unsupported fields") + ref = turn["collaboration_request"] + assert isinstance(ref, Mapping) + ref_recipient = ref["recipient"] + assert isinstance(ref_recipient, Mapping) + row = entry_fn(str(ref["request_id"]), ref_recipient) + requester = row["requester"] + assert isinstance(requester, Mapping) + with fenced_fn(session_id, requester, str(row["parent_request_id"])) as (facts, _): + validate_current_fn(row, facts) + core_fn("collaboration.source.original_conversation_access", facts) + if facts["recipient"] != row["recipient"]: + raise ValueError("original conversation recipient changed") + with _request_lock(root, str(row["request_id"]), None, Path(), force_exact=True): + row = entry_fn(str(row["request_id"]), ref_recipient) + core_fn("collaboration.project.continuation", {"entry": row, "turn": turn}) + view = view_fn(row) + if ( + view["control_state"] == "cancelled" + or answer["request_revision"] != view["revision"] + or answer["request_digest"] != view["revision_digest"] + ): + raise ValueError( + "original conversation answer belongs to a stale or " + "cancelled request" + ) + plan = core_fn( + "collaboration.request.assess", + { + "entry": row, + "actor_recipient": row["recipient"], + "recipient_active": True, + "observed_at": _now(), + "revision": answer["request_revision"], + "revision_digest": answer["request_digest"], + "decision": answer["decision"], + "reason": answer["reason"], + }, + ) + plan_entry = plan["entry"] + assert isinstance(plan_entry, dict) + if plan["changed"]: + _write( + _root(root) + / "entries" + / _hash({"recipient": row["recipient"]}) + / (str(row["request_id"]) + ".json"), + plan_entry, + ) + raw_rev = answer["request_revision"] + request_revision = raw_rev if isinstance(raw_rev, int) else int(str(raw_rev)) + receipt = record_result( + root, + row, + "conclusion", + str(answer["text"]), + request_revision=request_revision, + ) + return { + "schema_version": CHAT_AGENT_RESPONSE_SCHEMA_VERSION, + "message": answer["text"], + "proposals": [], + "protected_action": None, + "goal_draft": None, + "context_handoff": None, + "gate": None, + "unfinished_work": None, + "collaboration_result": receipt, + } + + +def execute_original_request_flow( + *, + session_id: str, + turn_id: str, + native_session: NativeSessionProtocol, + event_sink: EventSinkFn, + store: BindingSessionStoreProtocol, + validate_turn_fn: Callable[[str, BindingPayloadView], None], + entry_fn: Callable[[str, BindingPayloadView], BindingPayload], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + validate_current_fn: Callable[[BindingPayloadView, BindingPayloadView], None], + view_fn: Callable[[BindingPayloadView], BindingPayload], + inbox_fn: Callable[..., BindingPayload], + complete_answer_fn: Callable[ + [str, BindingPayloadView, BindingPayloadView], BindingPayload + ], + core_fn: CoreEffectFn, +) -> BindingPayload: + turn = store.load_turn(session_id, turn_id) + if turn is None: + raise ValueError("original conversation turn is unavailable") + validate_turn_fn(session_id, turn) + ref = turn["collaboration_request"] + assert isinstance(ref, Mapping) + ref_recipient = ref["recipient"] + assert isinstance(ref_recipient, Mapping) + row = entry_fn(str(ref["request_id"]), ref_recipient) + requester = row["requester"] + assert isinstance(requester, Mapping) + raw_answer = turn.get("collaboration_answer") + if raw_answer is None: + with fenced_fn(session_id, requester, str(row["parent_request_id"])) as ( + facts, + _, + ): + core_fn("collaboration.source.original_conversation_access", facts) + fenced_entry = entry_fn(str(ref["request_id"]), ref_recipient) + core_fn( + "collaboration.project.continuation", + {"entry": fenced_entry, "turn": turn}, + ) + inbox_items = inbox_fn( + ref_recipient, mark_read=True, request_id=str(row["request_id"]) + )["items"] + assert isinstance(inbox_items, list) + supplied = inbox_items[0] + assert isinstance(supplied, Mapping) + basis = { + key: supplied[key] + for key in ("request_revision", "request_revision_digest") + } + + @contextmanager + def start_guard() -> Iterator[None]: + with fenced_fn(session_id, requester, str(row["parent_request_id"])) as ( + facts, + _, + ): + guarded_entry = entry_fn(str(ref["request_id"]), ref_recipient) + validate_current_fn(guarded_entry, facts) + core_fn("collaboration.source.original_conversation_access", facts) + core_fn( + "collaboration.project.continuation", + {"entry": guarded_entry, "turn": turn}, + ) + current = view_fn(guarded_entry) + if ( + facts["recipient"] != ref_recipient + or current["control_state"] == "cancelled" + or current["revision"] != basis["request_revision"] + or current["revision_digest"] != basis["request_revision_digest"] + ): + raise ValueError( + "original conversation request changed before model input" + ) + yield + + message = ( + str(row["instruction"]) + + "\n\nPeer request (data):\n" + + json.dumps(supplied, ensure_ascii=False) + ) + answer_payload = native_session.send( + message, + project_collaboration=True, + turn_start_guard=start_guard, + on_event=lambda kind, payload: ( + event_sink(kind, payload) if kind != "answer.delta" else None + ), + ) + # Persist actual model output before result IO. Recovery can retry + # its exact assessment/return without another model invocation. + store.update_turn(session_id, turn_id, collaboration_answer=answer_payload) + answer: BindingPayloadView = answer_payload + else: + if not isinstance(raw_answer, Mapping): + raise ValueError("original conversation answer must be a mapping") + answer = raw_answer + response = complete_answer_fn(session_id, turn, answer) + event_sink("answer.delta", {"text": response["message"]}) + return response diff --git a/loopx/capabilities/native_chat/original_conversation_requests.py b/loopx/capabilities/native_chat/original_conversation_requests.py new file mode 100644 index 0000000000..a0e363a4e3 --- /dev/null +++ b/loopx/capabilities/native_chat/original_conversation_requests.py @@ -0,0 +1,538 @@ +"""Peer original-conversation request, management, and execution flows.""" +from __future__ import annotations + +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from pathlib import Path + +from ...chat_store import TERMINAL_TURN_STATES +from ...control_plane.collaboration.goal_instance_scope import CollaborationGoalScope +from ...file_lock import exclusive_file_lock +from .conversation_binding_contracts import ( + BindingAuthorityProtocol, + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingRowDict, + BindingSessionStoreProtocol, + EventSinkFn, + NativeSessionProtocol, + as_binding_payload, + core_effect, +) +from .original_conversation_execution import ( + complete_original_answer_flow, + execute_original_request_flow, + validate_current_original_flow, + validate_original_turn_flow, +) +from .original_conversation_views import ( + as_string_dict, + configure_original_grant_flow, + control_original_request_flow, + discover_original_recipients_flow, + original_management_view_flow, +) + + +class OriginalConversationRequests: + """Chat/source/store IO for the shared original-conversation request profile. + + The existing source policy, peer operation, request, revision, result and + Session FIFO remain their respective owners. No shadow queue is created. + """ + + def __init__(self, controller: BindingControllerProtocol) -> None: + self.controller: BindingControllerProtocol = controller + self.store: BindingSessionStoreProtocol = controller.store + self.root: Path = controller.coordination_runtime_root + bindings = controller.project_contexts.conversation_bindings + if bindings is None: + raise ValueError("original conversation bindings are unavailable") + self.bindings: BindingAuthorityProtocol = bindings + + _core = staticmethod(core_effect) + + def _policy(self) -> BindingPayload: + from ...control_plane.collaboration.inbox import _read, _root + + path = _root(self.root) / "policy.json" + if path.exists(): + return as_binding_payload(_read(path)) + return { + "schema_version": "loopx_manager_context_policy_v1", + "sources": {}, + } + + def _observation(self, session_id: str) -> tuple[BindingRowDict, BindingPayload]: + session = self.store.load_session(session_id) + if session is None: + raise ValueError("original project Session is unavailable") + raw_saved = session.get("project_context") + saved = raw_saved if isinstance(raw_saved, Mapping) else {} + current = self.bindings.read() + binding = next( + ( + row + for row in current["bindings"] + if row["binding_id"] == saved.get("binding_id") + ), + None, + ) + if binding is None: + raise ValueError("original conversation grant was revoked") + observed = dict(self.bindings.observe(binding["transport_ref"])) + return binding, observed + + def _recipient( + self, + session_id: str, + expected_binding: BindingPayloadView, + observation: BindingPayloadView, + policy: BindingPayloadView, + ) -> BindingPayload: + current = self.bindings.read() + if ( + next( + ( + row + for row in current["bindings"] + if row["binding_id"] == expected_binding["binding_id"] + ), + None, + ) + != expected_binding + ): + raise ValueError("original conversation binding changed during verification") + projects = self.bindings.projects + available_projects = projects.available() if projects is not None else [] + return self._core( + "collaboration.project.recipient", + { + "current": current, + "binding_id": expected_binding["binding_id"], + "observation": observation, + "available_projects": available_projects, + "session": self.store.load_session(session_id), + "policy": policy, + "sessions": [ + self.store.load_session(str(row["session_id"])) + for row in self.store.list_sessions() + ], + }, + ) + + @contextmanager + def _source( + self, + requester: BindingPayloadView, + parent_request_id: str, + *, + require_active: bool = True, + ) -> Iterator[tuple[BindingPayload, CollaborationGoalScope]]: + from ...control_plane.collaboration.goal_instance_scope import ( + collaboration_goal_scope, + ) + from ...control_plane.collaboration.inbox import _entry + from ...control_plane.collaboration.peer_context_observation import ( + require_parent_context_access, + ) + + if self.controller.registry_path is None: + raise ValueError("original conversation registry is unavailable") + raw_ref = requester.get("goal_ref") + ref_mapping = raw_ref if isinstance(raw_ref, Mapping) else {} + goal_id_val = ref_mapping.get("goal_id") + goal_id = goal_id_val if isinstance(goal_id_val, str) else "" + raw_agent_id = requester.get("agent_id") + agent_id = raw_agent_id if isinstance(raw_agent_id, str) else "" + caller_goal_ref = as_string_dict(raw_ref) + with collaboration_goal_scope( + self.controller.registry_path, + goal_id=goal_id, + agents=(agent_id,), + caller_goal_ref=caller_goal_ref, + require_active=require_active, + ) as scope: + if not scope.exact or requester != { + "goal_ref": scope.caller_goal_ref, + "agent_id": raw_agent_id, + }: + raise ValueError("an exact original requester is required") + parent = _entry( + self.root, + scope.goal_id, + str(requester["agent_id"]), + parent_request_id, + scope=scope, + ) + if "request_control" in parent and self._view(parent)["control_state"] in { + "cancelled", + "cancellation_pending", + }: + raise ValueError("the original source request was cancelled") + access = require_parent_context_access( + self.root, + self.controller.registry_path, + parent, + str(requester["agent_id"]), + scope=scope, + ) + yield ( + { + "requester": dict(requester), + "parent": parent, + "parent_request_id": parent_request_id, + "original_source_id": access["source_id"], + "parent_access_verified": True, + }, + scope, + ) + + @contextmanager + def _fenced( + self, + session_id: str, + requester: BindingPayloadView, + parent_request_id: str, + ) -> Iterator[tuple[BindingPayload, CollaborationGoalScope]]: + from ...control_plane.collaboration.inbox import _root + from ...control_plane.collaboration.source_policy_fence import ( + source_policy_fence, + ) + + binding, observed = self._observation(session_id) + # Every writer uses source -> Goal -> binding -> request -> Session. + # Provider IO precedes these fences; canonical identity is reread inside. + with ( + source_policy_fence(_root(self.root) / "policy.json"), + self._source(requester, parent_request_id) as (source, scope), + ): + with exclusive_file_lock( + self.bindings.path, operation="original_conversation_peer" + ): + policy = self._policy() + selected = self._recipient(session_id, binding, observed, policy) + yield ( + { + **source, + "policy": policy, + "recipient": selected["recipient"], + "current_recipient": selected["recipient"], + "policy_sha256": selected["policy_sha256"], + }, + scope, + ) + + def configure(self, session_id: str, body: BindingPayloadView) -> BindingPayload: + return configure_original_grant_flow( + root=self.root, + session_id=session_id, + body=body, + policy_fn=self._policy, + fenced_fn=self._fenced, + core_fn=self._core, + ) + + def management_view( + self, + session_id: str, + *, + search: str = "", + cursor: str | None = None, + ) -> BindingPayload: + return original_management_view_flow( + root=self.root, + bindings_path=self.bindings.path, + controller=self.controller, + session_id=session_id, + search=search, + cursor=cursor, + policy_fn=self._policy, + observation_fn=self._observation, + recipient_fn=self._recipient, + entry_fn=self._entry, + inbox_fn=self._inbox, + core_fn=self._core, + ) + + def discover( + self, requester: BindingPayloadView, parent_request_id: str + ) -> BindingPayload: + return discover_original_recipients_flow( + root=self.root, + controller=self.controller, + requester=requester, + parent_request_id=parent_request_id, + policy_fn=self._policy, + source_fn=self._source, + fenced_fn=self._fenced, + core_fn=self._core, + ) + + def publish(self, body: BindingPayloadView) -> BindingPayload: + from ...control_plane.collaboration.inbox import ( + _hash, + _now, + _read, + _request_lock, + _root, + _write, + ) + from ...control_plane.collaboration.peers import _operation_address + + recipient = body["recipient"] + requester = body["requester"] + if not isinstance(recipient, Mapping) or not isinstance(requester, Mapping): + raise ValueError("invalid original conversation request payload") + session_id = str(recipient["session_id"]) + with self._fenced( + session_id, requester, str(body["parent_request_id"]) + ) as (facts, scope): + if recipient != facts["recipient"]: + raise ValueError("original conversation recipient identity changed") + source_id, op_path = _operation_address( + self.root, scope, str(requester["agent_id"]), str(body["operation_id"]) + ) + # Native planning owns identity and replay. The old operation is + # consulted before any queue input or return route can be written. + prior = _read(op_path) if op_path.exists() else None + preview = self._core( + "collaboration.project.request", + { + **facts, + "source_id": source_id, + "request": {"recipient": recipient, "brief": body["brief"]}, + "observed_at": _now(), + }, + ) + preview_entry = preview["entry"] + assert isinstance(preview_entry, Mapping) + request_id = str(preview_entry["request_id"]) + path = ( + _root(self.root) + / "entries" + / _hash({"recipient": recipient}) + / (request_id + ".json") + ) + with _request_lock(self.root, request_id, None, op_path, force_exact=True): + prior = _read(op_path) if op_path.exists() else prior + plan = self._core( + "collaboration.project.request", + { + **facts, + "source_id": source_id, + "request": {"recipient": recipient, "brief": body["brief"]}, + "observed_at": _now(), + "operation": prior, + "entry": _read(path) if path.exists() else None, + }, + ) + row = plan["entry"] + route = plan["return_route"] + assert isinstance(row, dict) and isinstance(route, dict) + route_path = _root(self.root) / "roundtrips" / (request_id + ".json") + if route_path.exists() and _read(route_path) != route: + raise ValueError( + "original requester return route identity conflict" + ) + if prior is None: + operation_doc = plan["operation"] + assert isinstance(operation_doc, dict) + _write(op_path, operation_doc) + if not route_path.exists(): + _write(route_path, route) + if _read(route_path) != route: + raise OSError("original requester return route did not verify") + if not plan["replayed"]: + _write(path, row) + if _read(path) != row: + raise OSError("original conversation request did not verify") + view = self._view(row) + if view["control_state"] == "cancelled": + raise ValueError("original conversation request is cancelled") + turn, created = self._enqueue(row) + recovered = self._resume(session_id, turn, created) + return { + "ok": True, + "request_id": request_id, + "recipient": recipient, + "turn_id": turn["turn_id"], + "status": turn["status"], + "replayed": not created, + "goal_created": False, + "recovered_result": recovered, + } + + def _enqueue(self, row: BindingPayloadView) -> tuple[BindingPayload, bool]: + queue = self._core("collaboration.project.continuation", {"entry": row}) + recipient = row["recipient"] + assert isinstance(recipient, Mapping) + raw_request = queue["collaboration_request"] + collaboration_request = ( + as_binding_payload(raw_request) + if isinstance(raw_request, Mapping) + else None + ) + return self.store.create_queued_turn( + str(recipient["session_id"]), + client_turn_id=str(queue["client_turn_id"]), + message=str(queue["message"]), + origin="peer", + collaboration_request=collaboration_request, + ) + + def _stop_turns( + self, session_id: str, client_ids: list[str] + ) -> BindingPayload | None: + stopped: BindingPayload | None = None + for client_id in client_ids: + turn = self.store.turn_for_client(session_id, client_id) + if turn and turn["status"] not in TERMINAL_TURN_STATES: + stopped = self.controller.interrupt_turn( + session_id=session_id, turn_id=str(turn["turn_id"]) + ) + return stopped + + def _resume( + self, session_id: str, turn: BindingPayloadView, created: bool + ) -> object: + recovered: object = None + raw_answer = turn.get("collaboration_answer") + if not created and raw_answer is not None: + if not isinstance(raw_answer, Mapping): + raise ValueError("original conversation answer must be a mapping") + recovered = self._complete_answer(session_id, turn, raw_answer)[ + "collaboration_result" + ] + if turn["status"] not in TERMINAL_TURN_STATES: + projects = self.controller.project_contexts + loaded = self.store.load_session(session_id) + context = projects.session_context(loaded or {}) + self.controller.resume_session_queue( + session_id=session_id, + work_dir=Path(str(context["project"])), + objective=str(context.get("objective") or context["title"]), + ) + return recovered + + def _entry( + self, request_id: str, recipient: BindingPayloadView + ) -> BindingPayload: + from ...control_plane.collaboration.inbox import _entry + + return as_binding_payload( + _entry(self.root, None, None, request_id, recipient=dict(recipient)) + ) + + def _view(self, row: BindingPayloadView) -> BindingPayload: + raw_view = self._core( + "collaboration.request.control", + {"entry": row, "input": {"operation": "inspect"}, "source": {}}, + )["view"] + if not isinstance(raw_view, Mapping): + raise ValueError("invalid original conversation control view") + return as_binding_payload(raw_view) + + def _inbox( + self, + recipient: BindingPayloadView, + *, + mark_read: bool, + request_id: str | None = None, + cursor: str | None = None, + ) -> BindingPayload: + from ...control_plane.collaboration.inbox import _now + + raw_result = self._core( + "collaboration.inbox.read", + { + "runtime_root": str(self.root.resolve()), + "scope": { + "profile_id": "original_conversation_v0", + "recipient": recipient, + }, + "operation": "receiver_read" if mark_read else "pending", + "request_id": request_id, + "include_settled": not mark_read, + "cursor": cursor, + "observed_at": _now(), + "read_command": "original project Turn supplied context", + }, + large_local_snapshot=True, + )["result"] + if not isinstance(raw_result, Mapping): + raise ValueError("invalid original conversation inbox read") + return as_binding_payload(raw_result) + + def control(self, body: BindingPayloadView) -> BindingPayload: + return control_original_request_flow( + root=self.root, + controller=self.controller, + body=body, + entry_fn=self._entry, + fenced_fn=self._fenced, + enqueue_fn=self._enqueue, + resume_fn=self._resume, + stop_turns_fn=self._stop_turns, + core_fn=self._core, + ) + + def validate_turn(self, session_id: str, turn: BindingPayloadView) -> None: + validate_original_turn_flow( + session_id=session_id, + turn=turn, + entry_fn=self._entry, + fenced_fn=self._fenced, + validate_current_fn=self._validate_current, + view_fn=self._view, + core_fn=self._core, + ) + + def _validate_current( + self, row: BindingPayloadView, facts: BindingPayloadView + ) -> None: + validate_current_original_flow( + root=self.root, row=row, facts=facts, core_fn=self._core + ) + + def _complete_answer( + self, + session_id: str, + turn: BindingPayloadView, + answer: BindingPayloadView, + ) -> BindingPayload: + return complete_original_answer_flow( + root=self.root, + session_id=session_id, + turn=turn, + answer=answer, + entry_fn=self._entry, + fenced_fn=self._fenced, + validate_current_fn=self._validate_current, + view_fn=self._view, + core_fn=self._core, + ) + + def execute( + self, + session_id: str, + turn_id: str, + native_session: NativeSessionProtocol, + event_sink: EventSinkFn, + ) -> BindingPayload: + return execute_original_request_flow( + session_id=session_id, + turn_id=turn_id, + native_session=native_session, + event_sink=event_sink, + store=self.store, + validate_turn_fn=self.validate_turn, + entry_fn=self._entry, + fenced_fn=self._fenced, + validate_current_fn=self._validate_current, + view_fn=self._view, + inbox_fn=self._inbox, + complete_answer_fn=self._complete_answer, + core_fn=self._core, + ) diff --git a/loopx/capabilities/native_chat/original_conversation_views.py b/loopx/capabilities/native_chat/original_conversation_views.py new file mode 100644 index 0000000000..7431608ae0 --- /dev/null +++ b/loopx/capabilities/native_chat/original_conversation_views.py @@ -0,0 +1,466 @@ +"""Management, grant configuration, and recipient discovery views for peer requests.""" +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import AbstractContextManager, contextmanager +from pathlib import Path + +from ...control_plane.collaboration.goal_instance_scope import CollaborationGoalScope +from ...file_lock import exclusive_file_lock +from .conversation_binding_contracts import ( + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingRowDict, + CoreEffectFn, + InspectResultFn, + ReplyStatusFn, +) + + +def as_string_dict(value: object) -> dict[str, str] | None: + """Return a string-keyed string dict or ``None`` when any value is non-str.""" + if not isinstance(value, Mapping): + return None + result: dict[str, str] = {} + for key, item in value.items(): + if not isinstance(key, str) or not isinstance(item, str): + return None + result[key] = item + return result + + +def configure_original_grant_flow( + *, + root: Path, + session_id: str, + body: BindingPayloadView, + policy_fn: Callable[[], BindingPayload], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + core_fn: CoreEffectFn, +) -> BindingPayload: + from ...control_plane.collaboration.inbox import _read, _root, _write + from ...control_plane.collaboration.source_policy_fence import source_policy_fence + + enable = body.get("grant") + if not isinstance(enable, bool): + raise ValueError("grant must be an explicit boolean") + + def apply(facts: BindingPayloadView) -> BindingPayload: + plan = core_fn( + "collaboration.source.original_conversation_grant", + { + **facts, + "grant": enable, + "expected_policy_sha256": body.get("expected_policy_sha256"), + }, + ) + path = _root(root) / "policy.json" + policy_doc = plan["policy"] + if ( + body.get("execute") is True + and plan["would_change"] + and isinstance(policy_doc, dict) + ): + _write(path, policy_doc) + if _read(path) != policy_doc: + raise OSError("original conversation source grant did not verify") + return { + "ok": True, + "executed": body.get("execute") is True, + **{key: value for key, value in plan.items() if key != "policy"}, + } + + raw_requester = body["requester"] + if not isinstance(raw_requester, Mapping): + raise ValueError("an exact original requester is required") + parent_request_id = str(body["parent_request_id"]) + if enable: + with fenced_fn(session_id, raw_requester, parent_request_id) as (facts, _): + return apply(facts) + # An owner may revoke a retained grant even while its provider or source + # is unavailable. + with source_policy_fence(_root(root) / "policy.json"): + recipient = body["recipient"] + if ( + not isinstance(recipient, Mapping) + or recipient.get("session_id") != session_id + ): + raise ValueError("original conversation revocation scope mismatch") + return apply( + { + "policy": policy_fn(), + "recipient": recipient, + "requester": raw_requester, + "parent_request_id": parent_request_id, + "original_source_id": body["source_id"], + } + ) + + +def original_management_view_flow( + *, + root: Path, + bindings_path: Path, + controller: BindingControllerProtocol, + session_id: str, + search: str, + cursor: str | None, + policy_fn: Callable[[], BindingPayload], + observation_fn: Callable[[str], tuple[BindingRowDict, BindingPayload]], + recipient_fn: Callable[ + [str, BindingPayloadView, BindingPayloadView, BindingPayloadView], + BindingPayload, + ], + entry_fn: Callable[[str, BindingPayloadView], BindingPayload], + inbox_fn: Callable[..., BindingPayload], + core_fn: CoreEffectFn, +) -> BindingPayload: + from ...control_plane.collaboration import inbox + from ...control_plane.collaboration.inbox import _hash, _read, _root, result_paths + from ...control_plane.collaboration.source_policy_fence import source_policy_fence + + reply_status_fn: ReplyStatusFn = inbox.reply_status + inspect_result_fn: InspectResultFn = inbox.inspect_result_identity + + with source_policy_fence(_root(root) / "policy.json"): + policy = policy_fn() + view = core_fn( + "collaboration.source.original_conversation_grants", + {"policy": policy, "session_id": session_id}, + ) + raw_grants = view["grants"] + if not isinstance(raw_grants, list): + raise ValueError("invalid original conversation grants view") + for grant in raw_grants: + if not isinstance(grant, dict): + continue + requester = grant["requester"] + address = { + "goal_ref": requester["goal_ref"], + "agent_id": requester["agent_id"], + } + try: + parent = _read( + _root(root) + / "entries" + / _hash(address) + / (str(grant["parent_request_id"]) + ".json") + ) + if ( + parent.get("goal_ref") != requester["goal_ref"] + or parent.get("agent_id") != requester["agent_id"] + ): + raise ValueError("source grant parent identity changed") + brief = parent.get("brief") + purpose = ( + brief.get("purpose", parent.get("message", "")) + if isinstance(brief, Mapping) and brief + else parent.get("message", "") + ) + grant["source_purpose"] = purpose + except (ValueError, OSError): + grant["source_purpose"] = None + try: + binding, observed = observation_fn(session_id) + with exclusive_file_lock( + bindings_path, operation="original_conversation_inventory" + ): + view.update(recipient_fn(session_id, binding, observed, policy), available=True) + except (ValueError, KeyError, OSError) as exc: + return { + "ok": True, + **view, + "available": False, + "error": str(exc), + "candidates": [], + "requests": [], + } + candidates: list[BindingPayload] = [] + unreadable = 0 + overflow = False + # Content is projected only to the trusted local owner. A later grant + # still rechecks the exact registration, parent lineage and source. + for path in sorted((_root(root) / "entries").glob("*/*.json")): + try: + row = _read(path) + if ( + row.get("schema_version") != "loopx_manager_context_entry_v2" + or not row.get("goal_ref") + ): + continue + brief = row.get("brief") + purpose = ( + brief.get("purpose", row.get("message", "")) + if isinstance(brief, Mapping) and brief + else row.get("message", "") + ) + goal_ref = row["goal_ref"] + goal_id_str = ( + str(goal_ref["goal_id"]) if isinstance(goal_ref, Mapping) else "" + ) + if ( + search.strip().casefold() + not in " ".join( + (goal_id_str, str(row["agent_id"]), str(purpose)) + ).casefold() + ): + continue + candidates.append( + { + "requester": {"goal_ref": goal_ref, "agent_id": row["agent_id"]}, + "parent_request_id": row["request_id"], + "purpose": purpose, + } + ) + if len(candidates) == 128: + overflow = True + break + except (ValueError, OSError, KeyError): + unreadable += 1 + view.update( + candidates=candidates, + coverage={"unreadable": unreadable, "overflow": overflow}, + ) + raw_recipient = view["recipient"] + page = inbox_fn( + raw_recipient if isinstance(raw_recipient, Mapping) else {}, + mark_read=False, + cursor=cursor, + ) + view["requests"] = page["items"] + view["requests_has_more"] = page["has_more"] + view["requests_next_cursor"] = page["next_cursor"] + raw_requests = view["requests"] + if not isinstance(raw_requests, list): + return {"ok": True, **view} + for item in raw_requests: + if not isinstance(item, dict): + continue + item_recipient = item["recipient"] + if not isinstance(item_recipient, Mapping): + continue + results: list[BindingPayload] = [] + statuses = { + row.get("result_key", row["phase"]): row["status"] + for row in reply_status_fn(root, item) + } + entry = entry_fn(str(item["request_id"]), item_recipient) + queue = core_fn("collaboration.project.continuation", {"entry": entry}) + turn = controller.store.turn_for_client( + session_id, str(queue["client_turn_id"]) + ) + item["queue_status"] = turn.get("status") if turn else None + for path in result_paths(_root(root) / "replies" / str(item["request_id"])): + reply = _read(path) + if inspect_result_fn(reply, entry, path): + results.append( + { + "result_key": path.stem, + "text": reply["text"], + "decision": reply["decision"], + "request_revision": reply.get("request_revision", 1), + "delivery_status": statuses.get(path.stem, "queued"), + } + ) + item["returns"] = results + return {"ok": True, **view} + + +def discover_original_recipients_flow( + *, + root: Path, + controller: BindingControllerProtocol, + requester: BindingPayloadView, + parent_request_id: str, + policy_fn: Callable[[], BindingPayload], + source_fn: Callable[ + [BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + core_fn: CoreEffectFn, +) -> BindingPayload: + from ...control_plane.collaboration.inbox import _root + from ...control_plane.collaboration.source_policy_fence import source_policy_fence + + with ( + source_policy_fence(_root(root) / "policy.json"), + source_fn(requester, parent_request_id) as (_, _), + ): + grants = core_fn( + "collaboration.source.original_conversation_grants", + {"policy": policy_fn()}, + )["grants"] + recipients: list[BindingPayload] = [] + unavailable = 0 + if not isinstance(grants, list): + return {"ok": True, "recipients": recipients, "unavailable": unavailable} + for grant in grants: + if ( + not isinstance(grant, Mapping) + or grant.get("requester") != requester + or grant.get("parent_request_id") != parent_request_id + ): + continue + grant_recipient = grant["recipient"] + if not isinstance(grant_recipient, Mapping): + unavailable += 1 + continue + try: + with fenced_fn( + str(grant_recipient["session_id"]), + requester, + parent_request_id, + ) as (facts, _): + core_fn("collaboration.source.original_conversation_access", facts) + facts_recipient = facts["recipient"] + if facts_recipient != grant_recipient: + raise ValueError("original conversation recipient changed") + assert isinstance(facts_recipient, Mapping) + session = controller.store.load_session( + str(facts_recipient["session_id"]) + ) + title = (session or {}).get("title") or "Project conversation" + recipients.append({"recipient": facts_recipient, "title": title}) + except (ValueError, KeyError, OSError): + unavailable += 1 + return {"ok": True, "recipients": recipients, "unavailable": unavailable} + + +def control_original_request_flow( + *, + root: Path, + controller: BindingControllerProtocol, + body: BindingPayloadView, + entry_fn: Callable[[str, BindingPayloadView], BindingPayload], + fenced_fn: Callable[ + [str, BindingPayloadView, str], + AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]], + ], + enqueue_fn: Callable[[BindingPayloadView], tuple[BindingPayload, bool]], + resume_fn: Callable[[str, BindingPayloadView, bool], object], + stop_turns_fn: Callable[[str, list[str]], BindingPayload | None], + core_fn: CoreEffectFn, +) -> BindingPayload: + from ...control_plane.collaboration.goal_instance_scope import ( + collaboration_goal_scope, + ) + from ...control_plane.collaboration.inbox import ( + _hash, + _now, + _read, + _request_lock, + _root, + _write, + ) + from ...control_plane.collaboration.source_policy_fence import ( + source_policy_fence, + ) + + requester = body["requester"] + recipient = body["recipient"] + operation = body["control"] + parameters = body["parameters"] + if ( + not isinstance(requester, Mapping) + or not isinstance(recipient, Mapping) + or operation not in {"inspect", "revise", "cancel"} + or not isinstance(parameters, dict) + ): + raise ValueError("unsupported original conversation source control") + row = entry_fn(str(body["request_id"]), recipient) + if row["requester"] != requester: + raise ValueError("original requester identity changed") + session_id = str(recipient["session_id"]) + fence: AbstractContextManager[tuple[BindingPayload, CollaborationGoalScope]] + if operation == "revise": + fence = fenced_fn(session_id, requester, str(row["parent_request_id"])) + else: + # Revocation or a closed recipient must not remove the original + # source's ability to inspect/cancel its retained request. + @contextmanager + def retained_source() -> Iterator[tuple[BindingPayload, CollaborationGoalScope]]: + if controller.registry_path is None: + raise ValueError("original conversation registry is unavailable") + raw_ref = requester["goal_ref"] + caller_goal_ref = as_string_dict(raw_ref) + goal_id_val = raw_ref.get("goal_id") if isinstance(raw_ref, Mapping) else None + with ( + source_policy_fence(_root(root) / "policy.json"), + collaboration_goal_scope( + controller.registry_path, + goal_id=str(goal_id_val or ""), + agents=(str(requester["agent_id"]),), + caller_goal_ref=caller_goal_ref, + ) as scope, + ): + if not scope.exact: + raise ValueError("original requester exact instance is unavailable") + yield {}, scope + + fence = retained_source() + turn: BindingPayload | None = None + created = False + with ( + fence as (facts, _), + _request_lock(root, str(row["request_id"]), None, Path(), force_exact=True), + ): + current = entry_fn(str(row["request_id"]), recipient) + route = _read(_root(root) / "roundtrips" / (str(row["request_id"]) + ".json")) + core_fn("collaboration.project.return_route", {"entry": current, "route": route}) + if operation == "revise": + if recipient != facts["recipient"]: + raise ValueError("original conversation recipient changed") + core_fn("collaboration.source.original_conversation_access", facts) + plan = core_fn( + "collaboration.request.control", + { + "entry": current, + "input": {**parameters, "operation": operation}, + "source": { + "actor": "source", + "actor_agent_id": requester["agent_id"], + "actor_requester": requester, + "recipient_active": operation == "revise", + "observed_at": _now(), + }, + }, + ) + plan_entry = plan.get("entry") + if plan["changed"]: + assert isinstance(plan_entry, dict) + _write( + _root(root) + / "entries" + / _hash({"recipient": recipient}) + / (str(row["request_id"]) + ".json"), + plan_entry, + ) + if operation == "revise": + assert isinstance(plan_entry, Mapping) + turn, created = enqueue_fn(plan_entry) + stop = None + if operation == "revise": + assert turn is not None + resume_fn(session_id, turn, created) + elif operation == "cancel": + assert isinstance(plan_entry, Mapping) + queue = core_fn("collaboration.project.continuation", {"entry": plan_entry}) + superseded = queue["superseded_client_turn_ids"] + superseded_ids = ( + [str(item) for item in superseded] if isinstance(superseded, list) else [] + ) + stop = stop_turns_fn(session_id, [*superseded_ids, str(queue["client_turn_id"])]) + return { + "ok": True, + "request_control": plan["view"], + "replayed": plan.get("replayed", False), + "turn_stop": stop, + } diff --git a/tests/capabilities/test_conversation_bindings_contract.py b/tests/capabilities/test_conversation_bindings_contract.py new file mode 100644 index 0000000000..65c5e0e472 --- /dev/null +++ b/tests/capabilities/test_conversation_bindings_contract.py @@ -0,0 +1,724 @@ +"""Contract, key-presence, malformed-input, and single-read regressions for bindings.""" +from __future__ import annotations + +import ast +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager, contextmanager +import json +from pathlib import Path +import re +import sys + +import pytest + +from loopx import chat_store +from loopx.capabilities.native_chat import ( + conversation_binding_agents, + conversation_binding_contracts, + conversation_binding_delivery, + conversation_binding_flows, + conversation_bindings, + original_conversation_execution, + original_conversation_requests, + original_conversation_views, +) +from loopx.capabilities.native_chat.conversation_binding_contracts import ( + AppStewardTargetDict, + BindingAuthorityProtocol, + BindingControllerProtocol, + BindingPayload, + BindingPayloadView, + BindingRowDict, + BindingStateDict, + EventSinkFn, + LocalSessionSnapshotDict, + ProjectContextsProtocol, + ResolvedBindingDict, + as_binding_payload, + as_binding_row, + as_binding_state, +) +from loopx.capabilities.native_chat.conversation_bindings import ( + ChatConversationBindings, + OriginalConversationRequests, +) +from loopx.capabilities.native_chat.original_conversation_execution import ( + complete_original_answer_flow, + execute_original_request_flow, + validate_original_turn_flow, +) +from loopx.capabilities.native_chat.original_conversation_views import ( + original_management_view_flow, +) +from loopx.chat_store import ChatSessionStore +from loopx.control_plane.collaboration import inbox +from loopx.control_plane.collaboration.goal_instance_scope import CollaborationGoalScope + +CONTRACT_MODULES = ( + conversation_binding_contracts, + conversation_binding_agents, + conversation_binding_flows, + conversation_binding_delivery, + original_conversation_views, + original_conversation_execution, + original_conversation_requests, + conversation_bindings, +) + + +class _FakeProjects: + workspace_grant = "workspace_read" + conversation_bindings: BindingAuthorityProtocol | None = None + + def available(self) -> Sequence[BindingPayloadView]: + return [{"project_ref": "proj-1", "workspace_path": "/workspace/proj-1"}] + + def session_context(self, session: BindingPayload, /) -> BindingPayload: + del session + return {} + + +class _DummyStore: + def __init__( + self, + root: Path, + session: BindingPayload | None = None, + turn_doc: BindingPayload | None = None, + ) -> None: + self.root = root + self._session = session or {"session_id": "sess-1", "title": "Project Chat"} + self._turn_doc = turn_doc + self.updated_turns: list[tuple[str, str, dict[str, object]]] = [] + + def list_sessions( + self, + *, + goal_id: str | None = None, + agent_id: str | None = None, + channel_id: str | None = None, + ) -> Sequence[BindingPayload]: + del goal_id, agent_id, channel_id + return [dict(self._session)] + + def load_session(self, session_id: str, /) -> BindingPayload | None: + return dict(self._session) if session_id == self._session["session_id"] else None + + def load_turn(self, session_id: str, turn_id: str, /) -> BindingPayload | None: + del session_id, turn_id + return dict(self._turn_doc) if self._turn_doc is not None else None + + def queued_turns( + self, + session_id: str, + *, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, + ) -> Sequence[BindingPayload]: + del session_id, strict, include_reserved, capacity_at + return [] + + def select_session( + self, + *, + goal_id: str | None, + agent_id: str, + work_dir: Path, + mode: str = "resume_latest", + session_id: str | None = None, + channel_id: str | None = None, + executor_endpoint_id: str | None = None, + strict: bool = False, + include_reserved: bool = False, + capacity_at: str | None = None, + ) -> Sequence[BindingPayload]: + del ( + goal_id, + agent_id, + work_dir, + mode, + session_id, + channel_id, + executor_endpoint_id, + strict, + include_reserved, + capacity_at, + ) + return [] + + def update_session( + self, + session_id: str, + *, + expected_statuses: set[str] | None = None, + expected_upstream_thread_id: str | None = None, + metadata_review: bool = False, + quota_recovery: bool = False, + answer_review_admission: bool = False, + **changes: object, + ) -> BindingPayload: + del ( + expected_statuses, + expected_upstream_thread_id, + metadata_review, + quota_recovery, + answer_review_admission, + ) + return {"session_id": session_id, **changes} + + @contextmanager + def read_session_fenced(self, session_id: str, /) -> Iterator[BindingPayload | None]: + yield self.load_session(session_id) + + def iter_session_metadata( + self, + *, + goal_id: str | None = None, + agent_id: str | None = None, + channel_id: str | None = None, + ) -> Iterator[tuple[Path, BindingPayload]]: + del goal_id, agent_id, channel_id + return iter(()) + + def public_session(self, payload: BindingPayload, /) -> BindingPayload: + return dict(payload) + + def turn_for_client( + self, session_id: str, client_turn_id: str, / + ) -> BindingPayload | None: + del session_id, client_turn_id + return {"turn_id": "turn-1", "status": "completed"} + + def create_queued_turn( + self, + session_id: str, + *, + client_turn_id: str, + message: str, + origin: str = "external", + collaboration_request: BindingPayload | None = None, + ) -> tuple[BindingPayload, bool]: + del session_id, client_turn_id, message, origin, collaboration_request + return ({"turn_id": "t-new", "status": "queued"}, True) + + def update_turn( + self, + session_id: str, + turn_id: str, + *, + expected_statuses: set[str] | None = None, + **changes: object, + ) -> BindingPayload | None: + del expected_statuses + self.updated_turns.append((session_id, turn_id, dict(changes))) + return {"turn_id": turn_id, **changes} + + def resumable_session_candidates( + self, + *, + goal_id: str | None, + agent_id: str, + channel_id: str | None = None, + ) -> Sequence[BindingPayload]: + del goal_id, agent_id, channel_id + return [] + + +class _DummyController: + def __init__(self, root: Path, store: ChatSessionStore) -> None: + self.registry_path: Path | None = root / "registry.json" + self.coordination_runtime_root: Path = root + self.store: ChatSessionStore = store + self.project_contexts: ProjectContextsProtocol = _FakeProjects() + + def interrupt_turn(self, *, session_id: str, turn_id: str) -> BindingPayload: + return {"session_id": session_id, "turn_id": turn_id, "status": "stopped"} + + def resume_session_queue( + self, *, session_id: str, work_dir: Path, objective: str + ) -> None: + del session_id, work_dir, objective + + +def _make_bindings( + tmp_path: Path, *, projects: ProjectContextsProtocol | None = None +) -> ChatConversationBindings: + return ChatConversationBindings( + root=tmp_path, + project_contexts=projects, + observe=lambda ref: { + "transport_ref": ref, + "provider_ref": "prov-1", + "operator_ref": "op-1", + "verified": True, + }, + ) + + +def test_conversation_binding_modules_keep_size_zero_any_and_suppression_budgets() -> None: + root = Path(conversation_bindings.__file__).resolve().parent + assert ( + len(Path(conversation_bindings.__file__).read_text(encoding="utf-8").splitlines()) + <= 650 + ) + paths = [Path(mod.__file__ or "").resolve() for mod in CONTRACT_MODULES] + [ + Path(__file__).resolve() + ] + for idx, mod_file in enumerate(paths): + if idx < len(CONTRACT_MODULES): + assert mod_file.parent == root + src = mod_file.read_text(encoding="utf-8") + assert len(src.splitlines()) < 750, mod_file.name + tree = ast.parse(src) + anys = [ + node.lineno + for node in ast.walk(tree) + if isinstance(node, ast.Name) and node.id == "Any" + ] + assert anys == [], f"{mod_file.name} unexpectedly uses Any at lines {anys}" + assert not re.search(r"#\s*type:\s*ignore|\bnoqa\b", src), mod_file.name + + +def test_conversation_bindings_preserves_reexports_and_monkeypatch_seams( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + assert ( + conversation_bindings.OriginalConversationRequests + is OriginalConversationRequests + ) + assert conversation_bindings._atomic_write_json is chat_store._atomic_write_json + assert callable(conversation_bindings.exclusive_file_lock) + assert callable(conversation_bindings._read_json) + assert callable(conversation_bindings._host_ref) + assert callable(conversation_bindings._host_audiences) + assert callable(ChatConversationBindings._core) + assert callable(ChatConversationBindings.stop_recoveries) + + seen_ops: list[str] = [] + real_lock = conversation_bindings.exclusive_file_lock + + @contextmanager + def wrapped_lock(path: Path, *, operation: str = "lock") -> Iterator[Path]: + seen_ops.append(operation) + with real_lock(path, operation=operation) as held: + yield held + + monkeypatch.setattr(conversation_bindings, "exclusive_file_lock", wrapped_lock) + bindings = _make_bindings(tmp_path, projects=None) + bindings.select_app_steward(None, expected_revision=0) + assert seen_ops == ["select_app_steward"] + + # Immediate caller frame seen inside bindings.observe() during resolve() must be "resolve". + caller_frames: list[str] = [] + inner_observe = bindings.observe + + def framed_observe( + transport_ref: str, *, audience: str | None = None + ) -> BindingPayload: + caller_frames.append(sys._getframe(1).f_code.co_name) + return inner_observe(transport_ref, audience=audience) + + monkeypatch.setattr(bindings, "observe", framed_observe) + monkeypatch.setattr( + bindings, + "read", + lambda: BindingStateDict( + {"revision": 1, "bindings": [BindingRowDict({"binding_id": "b1", "transport_ref": "t1"})]} + ), + ) + monkeypatch.setattr(bindings, "_resolve_observed", lambda _c, _r, _o, _s: {"ok": True}) + bindings.resolve( + binding_id="b1", + source_ref="s1", + sender_ref="op-1", + private_human_message=True, + ) + assert caller_frames == ["resolve"] + + +def test_typed_contract_wrappers_preserve_dict_json_roundtrip() -> None: + row = as_binding_row({"binding_id": "b1", "transport_ref": "t1"}) + state = as_binding_state( + {"schema_version": "v0", "revision": 1, "bindings": [row]} + ) + payload = as_binding_payload({"key": "val"}) + assert payload == {"key": "val"} + assert isinstance(row, BindingRowDict) and isinstance(row, dict) + assert isinstance(state, BindingStateDict) and isinstance(state, dict) + assert json.loads(json.dumps(state))["bindings"][0]["binding_id"] == "b1" + assert isinstance( + ResolvedBindingDict( + { + "binding": row, + "channel_id": "c1", + "context": {}, + "owner_manager_audience": True, + } + ), + dict, + ) + assert isinstance( + AppStewardTargetDict({"binding_id": None, "session_id": None}), dict + ) + assert isinstance( + LocalSessionSnapshotDict({"sessions": [], "conversation_source": {}}), dict + ) + + +def test_legacy_missing_files_and_unselected_steward_without_projects( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + bindings = _make_bindings(tmp_path, projects=None) + state = bindings.read() + assert state == { + "schema_version": "loopx_chat_conversation_bindings_v0", + "revision": 0, + "bindings": [], + } + updated = bindings.select_app_steward(None, expected_revision=0) + assert updated["bindings"] == [] + + monkeypatch.setattr(bindings, "read", lambda: BindingStateDict({"revision": 0})) + with pytest.raises(ValueError, match="no longer authorized"): + bindings.resolve( + binding_id="missing", + source_ref="s1", + sender_ref="op-1", + private_human_message=True, + ) + + +def test_configure_preserves_goal_scope_key_presence_vs_none( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + bindings = _make_bindings(tmp_path, projects=_FakeProjects()) + existing_row = { + "binding_id": "b-keep", + "transport_ref": "app-1", + "provider_ref": "prov-1", + "operator_ref": "op-1", + "context_kind": "steward", + "project_ref": "proj-1", + "executor_endpoint_id": "codex", + "grant": "portfolio_read", + "enabled": True, + "goal_ids": ["g1"], + } + captured_candidates: list[BindingPayload] = [] + + def fake_core( + op: str, params: BindingPayloadView, **_kwargs: object + ) -> BindingPayload: + assert op == "collaboration.conversation.binding" + binding = params["binding"] + assert isinstance(binding, Mapping) + captured_candidates.append(dict(binding)) + return { + "changed": False, + "binding": dict(binding), + "state": dict(params["current"]) if isinstance(params["current"], Mapping) else {}, + } + + monkeypatch.setattr(bindings, "_core", fake_core) + + monkeypatch.setattr( + bindings, + "read", + lambda: BindingStateDict( + { + "schema_version": "loopx_chat_conversation_bindings_v0", + "revision": 1, + "bindings": [BindingRowDict(dict(existing_row))], + } + ), + ) + bindings.configure( + transport_ref="app-1", + project_ref="proj-1", + executor_endpoint_id="codex", + context_kind="steward", + goal_scope=None, + ) + assert "goal_scope" not in captured_candidates[-1] + + with_scope = {**existing_row, "goal_scope": "selected"} + monkeypatch.setattr( + bindings, + "read", + lambda: BindingStateDict( + { + "schema_version": "loopx_chat_conversation_bindings_v0", + "revision": 1, + "bindings": [BindingRowDict(with_scope)], + } + ), + ) + bindings.configure( + transport_ref="app-1", + project_ref="proj-1", + executor_endpoint_id="codex", + context_kind="steward", + goal_scope=None, + ) + assert captured_candidates[-1]["goal_scope"] == "selected" + + +def test_malformed_inputs_and_turn_key_presence_fail_closed(tmp_path: Path) -> None: + bindings = _make_bindings(tmp_path, projects=_FakeProjects()) + with pytest.raises(ValueError, match="steward Goal scope"): + bindings.configure( + transport_ref="app-1", + project_ref="proj-1", + executor_endpoint_id="codex", + context_kind="project", + goal_scope="selected", + ) + with pytest.raises(ValueError, match="workspace write authorization"): + bindings.configure( + transport_ref="app-1", + project_ref="proj-1", + executor_endpoint_id="codex", + context_kind="steward", + project_grant="workspace_write", + ) + with pytest.raises(ValueError, match="unsupported bound conversation input origin"): + with bindings.input_context( + {"binding_id": "b1"}, + origin="email", + session={"session_id": "s1"}, + store=_DummyStore(tmp_path), + ): + pass + + @contextmanager + def unused_fence( + _sid: str, _req: BindingPayloadView, _pid: str + ) -> Iterator[tuple[BindingPayload, CollaborationGoalScope]]: + if True: + raise AssertionError("fence must not run for invalid turn") + yield ( + {}, + CollaborationGoalScope( + registry_path=tmp_path / "registry.json", + goal_id="g1", + goal={}, + profile_id=None, + caller_goal_ref=None, + current_goal_ref=None, + ), + ) + + validate_original_turn_flow( + session_id="sess-1", + turn={"origin": "web"}, + entry_fn=lambda _rid, _rec: {}, + fenced_fn=unused_fence, + validate_current_fn=lambda _row, _facts: None, + view_fn=lambda _row: {}, + core_fn=lambda _op, _params, **_kw: {}, + ) + with pytest.raises(ValueError, match="peer Turn provenance is unavailable"): + validate_original_turn_flow( + session_id="sess-1", + turn={"origin": "web", "collaboration_request": None}, + entry_fn=lambda _rid, _rec: {}, + fenced_fn=unused_fence, + validate_current_fn=lambda _row, _facts: None, + view_fn=lambda _row: {}, + core_fn=lambda _op, _params, **_kw: {}, + ) + with pytest.raises(ValueError, match="unsupported fields"): + complete_original_answer_flow( + root=tmp_path, + session_id="sess-1", + turn={"origin": "peer"}, + answer={"text": "x"}, + entry_fn=lambda _rid, _rec: {}, + fenced_fn=unused_fence, + validate_current_fn=lambda _row, _facts: None, + view_fn=lambda _row: {}, + core_fn=lambda _op, _params, **_kw: {"required": ["text", "decision"]}, + ) + + +def test_management_view_reads_entry_once_per_request_with_multiple_replies( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + root = tmp_path / "coord" + replies_dir = inbox._root(root) / "replies" / "req-1" + replies_dir.mkdir(parents=True) + for idx, name in enumerate(("conclusion.json", "conclusion-00000001.json", "decision-00000002.json")): + (replies_dir / name).write_text( + json.dumps( + { + "text": f"result-{idx}", + "decision": "adopt", + "request_revision": idx + 1, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(inbox, "reply_status", lambda _root, _item: []) + monkeypatch.setattr(inbox, "inspect_result_identity", lambda _r, _e, _p: True) + + chat_store_instance = ChatSessionStore(tmp_path / "chat") + monkeypatch.setattr( + chat_store_instance, + "turn_for_client", + lambda _sid, _cid: {"turn_id": "turn-1", "status": "completed"}, + ) + controller: BindingControllerProtocol = _DummyController(root, chat_store_instance) + entry_calls: list[str] = [] + + def count_entry(request_id: str, recipient: BindingPayloadView) -> BindingPayload: + del recipient + entry_calls.append(request_id) + return {"request_id": request_id, "recipient": {"session_id": "sess-1"}} + + def fake_core( + op: str, params: BindingPayloadView, **_kwargs: object + ) -> BindingPayload: + del params + if op == "collaboration.source.original_conversation_grants": + return {"grants": []} + if op == "collaboration.project.continuation": + return {"client_turn_id": "ct-1"} + raise AssertionError(f"unexpected op: {op}") + + view = original_management_view_flow( + root=root, + bindings_path=tmp_path / "bindings.json", + controller=controller, + session_id="sess-1", + search="", + cursor=None, + policy_fn=lambda: { + "schema_version": "loopx_manager_context_policy_v1", + "sources": {}, + }, + observation_fn=lambda _sid: (BindingRowDict({"binding_id": "b1"}), {}), + recipient_fn=lambda _sid, _b, _o, _p: {"recipient": {"session_id": "sess-1"}}, + entry_fn=count_entry, + inbox_fn=lambda _rec, **_kw: { + "items": [{"request_id": "req-1", "recipient": {"session_id": "sess-1"}}], + "has_more": False, + "next_cursor": None, + }, + core_fn=fake_core, + ) + assert entry_calls == ["req-1"] + requests = view["requests"] + assert isinstance(requests, list) and len(requests[0]["returns"]) == 3 + + +def test_execute_start_guard_reads_guarded_entry_once(tmp_path: Path) -> None: + store = _DummyStore( + tmp_path, + turn_doc={ + "turn_id": "t1", + "origin": "peer", + "collaboration_request": { + "request_id": "req-1", + "recipient": {"session_id": "sess-1"}, + }, + }, + ) + entry_calls: list[str] = [] + + def count_entry(request_id: str, recipient: BindingPayloadView) -> BindingPayload: + del recipient + entry_calls.append(request_id) + return { + "request_id": request_id, + "parent_request_id": "p-1", + "requester": {"agent_id": "builder", "goal_ref": {"goal_id": "g1"}}, + "recipient": {"session_id": "sess-1"}, + "instruction": "Verify", + } + + @contextmanager + def fake_fence( + _sid: str, _req: BindingPayloadView, _pid: str + ) -> Iterator[tuple[BindingPayload, CollaborationGoalScope]]: + yield ( + {"recipient": {"session_id": "sess-1"}}, + CollaborationGoalScope( + registry_path=tmp_path / "registry.json", + goal_id="g1", + goal={}, + profile_id=None, + caller_goal_ref=None, + current_goal_ref=None, + ), + ) + + class _FakeNativeSession: + def send( + self, + user_message: str, + /, + *, + project_collaboration: bool = False, + turn_start_guard: Callable[[], AbstractContextManager[None]] | None = None, + on_event: EventSinkFn | None = None, + ) -> BindingPayload: + del user_message, project_collaboration, on_event + assert turn_start_guard is not None + with turn_start_guard(): + pass + return { + "text": "done", + "decision": "adopt", + "request_revision": 1, + "request_digest": "d1", + } + + events: list[tuple[str, BindingPayload]] = [] + res = execute_original_request_flow( + session_id="sess-1", + turn_id="t1", + native_session=_FakeNativeSession(), + event_sink=lambda kind, payload: events.append((kind, payload)), + store=store, + validate_turn_fn=lambda _sid, _t: None, + entry_fn=count_entry, + fenced_fn=fake_fence, + validate_current_fn=lambda _row, _facts: None, + view_fn=lambda _row: { + "control_state": "active", + "revision": 1, + "revision_digest": "d1", + }, + inbox_fn=lambda _rec, **_kw: { + "items": [{"request_revision": 1, "request_revision_digest": "d1"}] + }, + complete_answer_fn=lambda _sid, _t, _a: { + "message": "done", + "collaboration_result": {}, + }, + core_fn=lambda _op, _p, **_kw: {}, + ) + assert res["message"] == "done" + # Read 1: initial row; Read 2: fenced inbox fetch; Read 3: single read in start_guard. + assert len(entry_calls) == 3 + assert events == [("answer.delta", {"text": "done"})] + + +def test_real_chat_runtime_controller_satisfies_binding_controller_protocol( + tmp_path: Path, +) -> None: + from loopx.capabilities.native_chat.project_context import ChatProjectContexts + from loopx.chat_runtime import ChatRuntimeController + + contexts = ChatProjectContexts([]) + contexts.conversation_bindings = _make_bindings(tmp_path) + controller = ChatRuntimeController( + store=chat_store.ChatSessionStore(tmp_path / "chat"), + codex_bin="codex", + project_contexts=contexts, + ) + proto_controller: BindingControllerProtocol = controller + proto_contexts: ProjectContextsProtocol = controller.project_contexts + requests = OriginalConversationRequests(controller) + assert requests.controller is proto_controller + assert proto_contexts is controller.project_contexts