diff --git a/loopx/control_plane/chat_turn_acceptance.py b/loopx/control_plane/chat_turn_acceptance.py index 7b0b53e586..47d328d404 100644 --- a/loopx/control_plane/chat_turn_acceptance.py +++ b/loopx/control_plane/chat_turn_acceptance.py @@ -2,10 +2,11 @@ from __future__ import annotations +from collections.abc import Callable, Mapping, Sequence, Sized from dataclasses import dataclass import hashlib import json -from typing import Any +from typing import TypedDict from .effect_runtime import effect_runtime_result @@ -14,6 +15,14 @@ CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA = "loopx_chat_turn_acceptance_result_v0" CHAT_TURN_ACCEPTANCE_CAPSULE_SCHEMA = "loopx_chat_turn_acceptance_v0" TERMINAL_TURN_STATUSES = {"completed", "interrupted", "timed_out", "failed"} +_STEERING_RECEIPT_FIELDS = ( + "status", + "mode", + "expected_turn_id", + "active_turn_id", + "error_code", +) +_DISPATCH_NOT_REQUIRED_REASONS = {"already_started", "completion_in_progress", "terminal"} class ManagedTurnReplayConflictError(ValueError): @@ -24,47 +33,103 @@ def _sha256(value: str) -> str: return f"sha256:{hashlib.sha256(value.encode('utf-8')).hexdigest()}" -def _text_digest(value: Any) -> str: - if not isinstance(value, str): - return "invalid" - return _sha256(value) +_EMPTY_TEXT_DIGEST = _sha256("") +_NULL_JSON_DIGEST = _sha256("null") -def _json_digest(value: Any) -> str: +def _text_digest(value: object) -> str: + if not isinstance(value, str): + return "invalid" + return _EMPTY_TEXT_DIGEST if not value else _sha256(value) + + +def _json_digest(value: object) -> str: + if value is None: + return _NULL_JSON_DIGEST + payload: object = value + if isinstance(value, Mapping) and not isinstance(value, dict): + payload = {str(key): item for key, item in value.items()} + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + if not isinstance(value, list) or any( + isinstance(item, Mapping) and not isinstance(item, dict) for item in value + ): + payload = [ + {str(k): v for k, v in item.items()} + if isinstance(item, Mapping) and not isinstance(item, dict) + else item + for item in value + ] try: encoded = json.dumps( - value, - ensure_ascii=False, - allow_nan=False, - separators=(",", ":"), - sort_keys=True, + payload, ensure_ascii=False, allow_nan=False, separators=(",", ":"), sort_keys=True ) except (TypeError, ValueError): return "invalid" return _sha256(encoded) -def _acceptance_facts(turn: dict[str, Any]) -> dict[str, Any] | None: +def _as_object_dict(value: object, *, label: str) -> dict[str, object]: + if not isinstance(value, Mapping): + raise ValueError(f"{label} result must be an object") + return {str(key): item for key, item in value.items()} + + +def _session_projection(session: Mapping[str, object] | None) -> dict[str, object] | None: + if session is None: + return None + return {"status": session.get("status"), "active_turn_id": session.get("active_turn_id")} + + +def _turn_status_projection(turn: Mapping[str, object] | None) -> dict[str, object] | None: + if turn is None: + return None + return {"turn_id": turn.get("turn_id"), "status": turn.get("status")} + + +def _queued_turn_base(turn: Mapping[str, object]) -> dict[str, object]: + return { + "turn_id": turn["turn_id"], + "status": turn["status"], + "origin": turn.get("origin"), + "loopx_execution": turn.get("loopx_execution", False), + "has_collaboration_request": turn.get("collaboration_request") is not None, + "has_external_agent_target": turn.get("external_agent_target") is not None, + "reservation": turn.get("_queue_steering"), + "mutation": turn.get("_queue_mutation"), + } + + +def _single_match( + rows: Sequence[Mapping[str, object]], + predicate: Callable[[Mapping[str, object]], bool], +) -> tuple[int, Mapping[str, object] | None]: + count = 0 + first: Mapping[str, object] | None = None + for row in rows: + if predicate(row): + count += 1 + if count == 1: + first = row + return count, first + + +def _acceptance_facts(turn: Mapping[str, object]) -> dict[str, object] | None: acceptance = turn.get("_acceptance") if acceptance is None: return None - if not isinstance(acceptance, dict): + if not isinstance(acceptance, Mapping): return {"schema_version": None} return { "schema_version": acceptance.get("schema_version"), "phase": acceptance.get("phase"), "request_sha256": acceptance.get("request_sha256"), "message_id": acceptance.get("message_id"), - "display_message_sha256": _text_digest( - acceptance.get("display_message") - ), - "attachments_sha256": _json_digest( - acceptance.get("attachments") or None - ), + "display_message_sha256": _text_digest(acceptance.get("display_message")), + "attachments_sha256": _json_digest(acceptance.get("attachments") or None), } -def _turn_facts(turn: dict[str, Any] | None) -> dict[str, Any] | None: +def _turn_facts(turn: Mapping[str, object] | None) -> dict[str, object] | None: if turn is None: return None return { @@ -79,59 +144,31 @@ def _turn_facts(turn: dict[str, Any] | None) -> dict[str, Any] | None: } -def _transcript_facts( - messages: list[dict[str, Any]], - turn_id: str | None, -) -> dict[str, Any]: +def _transcript_facts(messages: Sequence[Mapping[str, object]], turn_id: str | None) -> dict[str, object]: if turn_id is None: return {"count": 0} - matching = [ - row - for row in messages - if row.get("role") == "user" and row.get("turn_id") == turn_id - ] - if len(matching) != 1: - return {"count": len(matching)} - message = matching[0] + count, msg = _single_match(messages, lambda row: row.get("role") == "user" and row.get("turn_id") == turn_id) + if count != 1 or msg is None: + return {"count": count} return { "count": 1, - "message_id": message.get("message_id"), - "display_message_sha256": _text_digest(message.get("text")), - "attachments_sha256": _json_digest( - message.get("attachments") or None - ), - "origin": message.get("origin"), + "message_id": msg.get("message_id"), + "display_message_sha256": _text_digest(msg.get("text")), + "attachments_sha256": _json_digest(msg.get("attachments") or None), + "origin": msg.get("origin"), } -def _queued_event_facts(events: list[dict[str, Any]]) -> dict[str, Any]: - queued = [event for event in events if event.get("kind") == "turn.queued"] - if len(queued) != 1: - return {"count": len(queued)} - return { - "count": 1, - "payload_sha256": _json_digest(queued[0].get("payload")), - } +def _queued_event_facts(events: Sequence[Mapping[str, object]]) -> dict[str, object]: + count, event = _single_match(events, lambda row: row.get("kind") == "turn.queued") + return {"count": count} if count != 1 or event is None else {"count": 1, "payload_sha256": _json_digest(event.get("payload"))} -def _prepared_turn_facts( - turns: list[dict[str, Any]], -) -> dict[str, Any]: - prepared = [ - turn - for turn in turns - if ( - "_acceptance" in turn - and turn.get("status") not in TERMINAL_TURN_STATUSES - ) - ] - if len(prepared) != 1: - return {"count": len(prepared)} - return { - "count": 1, - "turn_id": prepared[0].get("turn_id"), - "client_turn_id": prepared[0].get("client_turn_id"), - } +def _prepared_turn_facts(turns: Sequence[Mapping[str, object]]) -> dict[str, object]: + count, turn = _single_match(turns, lambda row: "_acceptance" in row and row.get("status") not in TERMINAL_TURN_STATUSES) + if count != 1 or turn is None: + return {"count": count} + return {"count": 1, "turn_id": turn.get("turn_id"), "client_turn_id": turn.get("client_turn_id")} @dataclass(frozen=True) @@ -157,137 +194,172 @@ class ManagedTurnAcceptancePlan: @dataclass(frozen=True) class AcceptedManagedTurn: - turn: dict[str, Any] + turn: dict[str, object] created: bool dispatch_required: bool dispatch_reason: str | None -def _required_string(payload: dict[str, Any], field: str) -> str: +class QueuedChatMutationEvent(TypedDict): + """Event emitted by TypeScript queue mutation planning.""" + + kind: str + payload: dict[str, object] + + +class QueuedChatMutationPlan(TypedDict, total=False): + """Typed plan returned by `chat.queue.mutate` for storage application.""" + + action: str + error_code: str + receipt: dict[str, object] + message_patch: dict[str, object] + turn_patch: dict[str, object] + event: QueuedChatMutationEvent + + +def _required_string(payload: Mapping[str, object], field: str) -> str: value = payload.get(field) if not isinstance(value, str) or not value: raise ValueError(f"chat turn acceptance result has invalid {field}") return value +def _required_bool(payload: object, field: str) -> bool: + if not isinstance(payload, Mapping): + raise ValueError("chat turn acceptance result must be an object") + value = payload.get(field) + if not isinstance(value, bool): + raise ValueError(f"chat turn acceptance result has invalid {field}") + return value + + def queued_chat_turn_ids( - turns: list[dict[str, Any]], active_turn_id: str | None, *, + turns: Sequence[Mapping[str, object]], active_turn_id: str | None, *, include_reserved: bool = False, capacity_at: str | None = None, ) -> list[str]: """Project storage observations to the typed queue/Turn owner.""" - return effect_runtime_result("chat.queue.select", { - "active_turn_id": active_turn_id, "include_reserved": include_reserved, - "capacity_at": capacity_at, - "turns": [{"turn_id": t["turn_id"], "status": t["status"], - "expires_at": t.get("expires_at"), "reservation": t.get("_queue_steering"), - "mutation": t.get("_queue_mutation")} for t in turns], - })["turn_ids"] + raw_result: object = effect_runtime_result("chat.queue.select", { + "active_turn_id": active_turn_id, "include_reserved": include_reserved, "capacity_at": capacity_at, + "turns": [{"turn_id": t["turn_id"], "status": t["status"], "expires_at": t.get("expires_at"), + "reservation": t.get("_queue_steering"), "mutation": t.get("_queue_mutation")} for t in turns], + }) + if not isinstance(raw_result, Mapping) or not isinstance(raw_ids := raw_result.get("turn_ids"), list): + raise ValueError("chat queue selection result has invalid turn_ids") + turn_ids: list[str] = [] + for item in raw_ids: + if not isinstance(item, str): + raise ValueError("chat queue selection result has invalid turn_ids") + turn_ids.append(item) + return turn_ids -def plan_native_mention_ingress(**facts: object) -> dict[str, Any]: +def plan_native_mention_ingress(**facts: object) -> dict[str, object]: """Ask the shared queue/steering owner to select one exact ingress.""" - return effect_runtime_result("chat.queue.mention", facts) + return _as_object_dict(effect_runtime_result("chat.queue.mention", facts), label="chat mention ingress") + + +def _steering_attachment_count(attachments: object) -> int: + """Count queued attachments for text-only steering, failing closed on unexpected shapes.""" + if attachments is None: + return 0 + if isinstance(attachments, Sequence) and not isinstance(attachments, (str, bytes, bytearray, memoryview)): + return len(attachments) + if isinstance(attachments, Sized) and len(attachments) > 0: + return len(attachments) + raise ValueError("queued turn attachments must be null or a sequence") def plan_queued_chat_steering( - session: dict[str, Any], turn: dict[str, Any], active: dict[str, Any] | None, - receipt: dict[str, Any] | None, *, ingress_id: str, operation_id: str, target: str, phase: str, + session: Mapping[str, object], turn: Mapping[str, object], active: Mapping[str, object] | None, + receipt: Mapping[str, object] | None, *, ingress_id: str, operation_id: str, target: str, phase: str, web_origin_only: bool = False, -) -> dict[str, Any]: - return effect_runtime_result("chat.queue.steer", { +) -> dict[str, object]: + session_payload = _session_projection(session) or {} + session_payload["web_origin_only"] = web_origin_only + turn_payload = _queued_turn_base(turn) + turn_payload["attachment_count"] = _steering_attachment_count(turn.get("attachments")) + raw_result: object = effect_runtime_result("chat.queue.steer", { "phase": phase, "request": {"client_ingress_id": ingress_id, "operation_id": operation_id, "target_turn_id": target}, - "session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id"), - "web_origin_only": web_origin_only}, - "active_status": (active or {}).get("status"), - "turn": {"turn_id": turn["turn_id"], "status": turn["status"], - "origin": turn.get("origin"), "loopx_execution": turn.get("loopx_execution", False), - "has_collaboration_request": turn.get("collaboration_request") is not None, - "has_external_agent_target": turn.get("external_agent_target") is not None, - "attachment_count": len(turn.get("attachments") or []), - "reservation": turn.get("_queue_steering"), "mutation": turn.get("_queue_mutation")}, - "receipt": ({key: receipt.get(key) for key in ( - "status", "mode", "expected_turn_id", "active_turn_id", "error_code", - )} if receipt is not None else None), + "session": session_payload, + "active_status": active.get("status") if active is not None else None, + "turn": turn_payload, + "receipt": ({k: receipt.get(k) for k in _STEERING_RECEIPT_FIELDS} if receipt is not None else None), "receipt_message_matches": receipt is not None and receipt.get("message") == turn.get("message"), }) - - -def plan_queued_chat_mutation(session: dict[str, Any], turn: dict[str, Any], request: dict[str, Any]) -> dict[str, Any]: - return effect_runtime_result("chat.queue.mutate", { - "session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id")}, - "turn": {"turn_id": turn["turn_id"], "status": turn["status"], "origin": turn.get("origin"), - "has_collaboration_request": turn.get("collaboration_request") is not None, - "has_external_agent_target": turn.get("external_agent_target") is not None, - "loopx_execution": turn.get("loopx_execution", False), "has_acceptance": "_acceptance" in turn, - "input_revision": turn.get("input_revision", 0), "reservation": turn.get("_queue_steering"), - "mutation": turn.get("_queue_mutation"), "operations": turn.get("_queue_operations", [])}, - "request": request, - }) - - -def _required_bool(payload: dict[str, Any], field: str) -> bool: - value = payload.get(field) - if not isinstance(value, bool): - raise ValueError(f"chat turn acceptance result has invalid {field}") - return value - - -def managed_turn_execution_allowed( - session: dict[str, Any] | None, turn: dict[str, Any] | None, -) -> bool: + return _as_object_dict(raw_result, label="chat queued steering") + + +def _decode_mutation_event(value: object) -> QueuedChatMutationEvent: + raw_event = _as_object_dict(value, label="chat queued mutation event") + kind = raw_event.get("kind") + if not isinstance(kind, str) or not kind: + raise ValueError("chat queued mutation event kind must be a string") + return {"kind": kind, "payload": _as_object_dict(raw_event.get("payload"), label="chat queued mutation event payload")} + + +def plan_queued_chat_mutation( + session: Mapping[str, object], turn: Mapping[str, object], request: Mapping[str, object] +) -> QueuedChatMutationPlan: + turn_payload = _queued_turn_base(turn) + turn_payload.update({"has_acceptance": "_acceptance" in turn, "input_revision": turn.get("input_revision", 0), "operations": turn.get("_queue_operations", [])}) + decoded = _as_object_dict( + effect_runtime_result("chat.queue.mutate", { + "session": _session_projection(session), + "turn": turn_payload, + "request": request if isinstance(request, dict) else _as_object_dict(request, label="request"), + }), + label="chat queued mutation", + ) + plan: QueuedChatMutationPlan = {} + if isinstance(action := decoded.get("action"), str): + plan["action"] = action + if isinstance(error_code := decoded.get("error_code"), str): + plan["error_code"] = error_code + if decoded.get("receipt") is not None: + plan["receipt"] = _as_object_dict(decoded.get("receipt"), label="chat queued mutation receipt") + if decoded.get("message_patch") is not None: + plan["message_patch"] = _as_object_dict(decoded.get("message_patch"), label="chat queued mutation message_patch") + if decoded.get("turn_patch") is not None: + plan["turn_patch"] = _as_object_dict(decoded.get("turn_patch"), label="chat queued mutation turn_patch") + if decoded.get("event") is not None: + plan["event"] = _decode_mutation_event(decoded.get("event")) + return plan + + +def managed_turn_execution_allowed(session: Mapping[str, object] | None, turn: Mapping[str, object] | None) -> bool: """Ask the existing typed Turn owner about the current durable claim.""" - result = effect_runtime_result("chat.turn.execution_allowed", { - "session": ({"status": session.get("status"), - "active_turn_id": session.get("active_turn_id")} - if session is not None else None), - "turn": ({"turn_id": turn.get("turn_id"), "status": turn.get("status")} - if turn is not None else None), - }) - return _required_bool(result, "allowed") + return _required_bool(effect_runtime_result("chat.turn.execution_allowed", {"session": _session_projection(session), "turn": _turn_status_projection(turn)}), "allowed") def managed_turn_recovery_allowed( - session: dict[str, Any] | None, turn: dict[str, Any] | None, - *, managed: bool, owner_dead: bool, + session: Mapping[str, object] | None, turn: Mapping[str, object] | None, *, managed: bool, owner_dead: bool ) -> bool: """Project process observations to the same typed Turn lifecycle owner.""" - result = effect_runtime_result("chat.turn.recovery_allowed", { - "session": ({"status": session.get("status"), - "active_turn_id": session.get("active_turn_id")} - if session is not None else None), - "turn": ({"turn_id": turn.get("turn_id"), "status": turn.get("status")} - if turn is not None else None), - "managed": managed, - "owner_dead": owner_dead, - }) - return _required_bool(result, "allowed") + return _required_bool( + effect_runtime_result("chat.turn.recovery_allowed", {"session": _session_projection(session), "turn": _turn_status_projection(turn), "managed": managed, "owner_dead": owner_dead}), + "allowed", + ) -def _raise_rejection(result: dict[str, Any]) -> None: +def _raise_rejection(result: Mapping[str, object]) -> None: code = result.get("code") if code in {"session_not_found", "session_closed"}: raise KeyError("chat session was not found") if code == "request_conflict": - raise ManagedTurnReplayConflictError( - "client_turn_id already belongs to a different request" - ) + raise ManagedTurnReplayConflictError("client_turn_id already belongs to a different request") if code == "active_turn_conflict": - active_turn_id = result.get("active_turn_id") - raise RuntimeError( - str(active_turn_id or "chat session already has an active turn") - ) + raise RuntimeError(str(result.get("active_turn_id") or "chat session already has an active turn")) if code == "original_request_unavailable": raise ValueError("client_turn_id original request is unavailable") if code == "durable_state_conflict": - raise ManagedTurnReplayConflictError( - "chat turn acceptance state is inconsistent" - ) + raise ManagedTurnReplayConflictError("chat turn acceptance state is inconsistent") raise ValueError("chat turn acceptance returned an unsupported rejection") -def _decode_plan(value: Any) -> ManagedTurnAcceptancePlan: - if not isinstance(value, dict): +def _decode_plan(value: object) -> ManagedTurnAcceptancePlan: + if not isinstance(value, Mapping): raise ValueError("chat turn acceptance result must be an object") if value.get("schema_version") != CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA: raise ValueError("chat turn acceptance result schema is unsupported") @@ -298,22 +370,15 @@ def _decode_plan(value: Any) -> ManagedTurnAcceptancePlan: disposition = _required_string(value, "disposition") if disposition not in {"created", "repaired", "replayed"}: raise ValueError("chat turn acceptance disposition is unsupported") - writes = value.get("writes") - dispatch = value.get("dispatch") - if not isinstance(writes, dict) or not isinstance(dispatch, dict): + writes, dispatch = value.get("writes"), value.get("dispatch") + if not isinstance(writes, Mapping) or not isinstance(dispatch, Mapping): raise ValueError("chat turn acceptance result is incomplete") - dispatch_kind = dispatch.get("kind") + dispatch_kind, dispatch_reason = dispatch.get("kind"), dispatch.get("reason") if dispatch_kind not in {"required", "not_required"}: raise ValueError("chat turn acceptance dispatch kind is unsupported") - dispatch_reason = dispatch.get("reason") - if dispatch_kind == "not_required": - if dispatch_reason not in { - "already_started", - "completion_in_progress", - "terminal", - }: - raise ValueError("chat turn acceptance dispatch reason is unsupported") - elif dispatch_reason is not None: + if (dispatch_kind == "not_required" and dispatch_reason not in _DISPATCH_NOT_REQUIRED_REASONS) or ( + dispatch_kind == "required" and dispatch_reason is not None + ): raise ValueError("chat turn acceptance dispatch reason is unsupported") return ManagedTurnAcceptancePlan( disposition=disposition, @@ -325,83 +390,35 @@ def _decode_plan(value: Any) -> ManagedTurnAcceptancePlan: prepare_turn=_required_bool(writes, "prepare_turn"), activate_session=_required_bool(writes, "activate_session"), append_message=_required_bool(writes, "append_message"), - append_queued_event=_required_bool( - writes, - "append_queued_event", - ), + append_queued_event=_required_bool(writes, "append_queued_event"), settle_turn=_required_bool(writes, "settle_turn"), ), dispatch_required=dispatch_kind == "required", - dispatch_reason=( - str(dispatch_reason) - if dispatch_kind == "not_required" - else None - ), + dispatch_reason=str(dispatch_reason) if dispatch_kind == "not_required" else None, ) def plan_managed_turn_acceptance( - *, - session_id: str, - client_turn_id: str, - message: str, - display_message: str, - attachments: list[dict[str, Any]] | None, - origin: str, - loopx_execution: bool, - loopx_request: dict[str, object] | None, - candidate_turn_id: str, - candidate_message_id: str, - accepted_at: str, - session: dict[str, Any] | None, - active_turn: dict[str, Any] | None, - matching_turn: dict[str, Any] | None, - turns: list[dict[str, Any]], - messages: list[dict[str, Any]], - queued_events: list[dict[str, Any]], + *, session_id: str, client_turn_id: str, message: str, display_message: str, + attachments: Sequence[Mapping[str, object]] | None, origin: str, loopx_execution: bool, + loopx_request: Mapping[str, object] | None, candidate_turn_id: str, candidate_message_id: str, + accepted_at: str, session: Mapping[str, object] | None, active_turn: Mapping[str, object] | None, + matching_turn: Mapping[str, object] | None, turns: Sequence[Mapping[str, object]], + messages: Sequence[Mapping[str, object]], queued_events: Sequence[Mapping[str, object]], ) -> ManagedTurnAcceptancePlan: request = { "schema_version": CHAT_TURN_ACCEPTANCE_REQUEST_SCHEMA, "request": { - "session_id": session_id, - "client_turn_id": client_turn_id, - "execution_message_sha256": _text_digest(message), - "display_message_sha256": _text_digest(display_message), - "attachments_sha256": _json_digest(attachments or None), - "origin": origin, - "loopx_execution": loopx_execution, - "loopx_request_sha256": _json_digest(loopx_request), + "session_id": session_id, "client_turn_id": client_turn_id, + "execution_message_sha256": _text_digest(message), "display_message_sha256": _text_digest(display_message), + "attachments_sha256": _json_digest(attachments or None), "origin": origin, + "loopx_execution": loopx_execution, "loopx_request_sha256": _json_digest(loopx_request), }, - "candidate": { - "turn_id": candidate_turn_id, - "message_id": candidate_message_id, - "accepted_at": accepted_at, - }, - "session": ( - { - "status": session.get("status"), - "active_turn_id": session.get("active_turn_id"), - } - if session is not None - else None - ), - "active_turn": ( - { - "turn_id": active_turn.get("turn_id"), - "status": active_turn.get("status"), - } - if active_turn is not None - else None - ), + "candidate": {"turn_id": candidate_turn_id, "message_id": candidate_message_id, "accepted_at": accepted_at}, + "session": _session_projection(session), + "active_turn": _turn_status_projection(active_turn), "matching_turn": _turn_facts(matching_turn), - "transcript": _transcript_facts( - messages, - ( - str(matching_turn.get("turn_id")) - if matching_turn is not None - else None - ), - ), + "transcript": _transcript_facts(messages, str(matching_turn.get("turn_id")) if matching_turn is not None else None), "queued_event": _queued_event_facts(queued_events), "prepared_turn": _prepared_turn_facts(turns), } diff --git a/tests/control_plane/test_chat_turn_acceptance_contract.py b/tests/control_plane/test_chat_turn_acceptance_contract.py new file mode 100644 index 0000000000..1d014a07a0 --- /dev/null +++ b/tests/control_plane/test_chat_turn_acceptance_contract.py @@ -0,0 +1,377 @@ +"""Contract, zero-Any, MappingProxyType, and error-path tests for chat_turn_acceptance.""" + +from __future__ import annotations + +import ast +import json +from pathlib import Path +from types import MappingProxyType +import pytest + +from loopx.chat_store import ChatSessionStore +from loopx.control_plane import chat_turn_acceptance as cta + + +REPO_ROOT = Path(__file__).resolve().parents[2] +TARGET_PATH = REPO_ROOT / "loopx" / "control_plane" / "chat_turn_acceptance.py" + + +def test_chat_turn_acceptance_zero_any_budget_and_exports() -> None: + for rel, max_loc in ( + ("loopx/control_plane/chat_turn_acceptance.py", 450), + ("tests/control_plane/test_chat_turn_acceptance_contract.py", 400), + ): + src = (REPO_ROOT / rel).read_text(encoding="utf-8") + assert len(src.splitlines()) <= max_loc, rel + tree = ast.parse(src) + anys = [n for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id == "Any"] + assert anys == [], rel + assert ("type: " + "ignore") not in src, rel + assert ("no" + "qa") not in src, rel + + for symbol in ( + "CHAT_TURN_ACCEPTANCE_REQUEST_SCHEMA", + "CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA", + "CHAT_TURN_ACCEPTANCE_CAPSULE_SCHEMA", + "TERMINAL_TURN_STATUSES", + "ManagedTurnReplayConflictError", + "ManagedTurnAcceptanceWrites", + "ManagedTurnAcceptancePlan", + "AcceptedManagedTurn", + "QueuedChatMutationPlan", + "queued_chat_turn_ids", + "plan_native_mention_ingress", + "plan_queued_chat_steering", + "plan_queued_chat_mutation", + "managed_turn_execution_allowed", + "managed_turn_recovery_allowed", + "plan_managed_turn_acceptance", + ): + assert hasattr(cta, symbol), symbol + + +def test_digest_and_fact_projections_cover_fast_paths_and_multi_matches() -> None: + assert cta._text_digest(None) == "invalid" + assert cta._text_digest(123) == "invalid" + assert cta._text_digest("") == cta._EMPTY_TEXT_DIGEST + assert cta._json_digest(None) == cta._NULL_JSON_DIGEST + assert cta._json_digest(object()) == "invalid" + assert cta._json_digest(MappingProxyType({"a": 1})) == cta._json_digest({"a": 1}) + assert cta._json_digest((MappingProxyType({"k": "v"}),)) == cta._json_digest([{"k": "v"}]) + + assert cta._acceptance_facts({}) is None + assert cta._acceptance_facts({"_acceptance": "bad"}) == {"schema_version": None} + + msgs = ( + MappingProxyType({"role": "user", "turn_id": "t1", "message_id": "m1", "text": ""}), + MappingProxyType({"role": "assistant", "turn_id": "t1", "text": "ok"}), + ) + assert cta._transcript_facts(msgs, None) == {"count": 0} + single = cta._transcript_facts(msgs, "t1") + assert single["count"] == 1 and single["message_id"] == "m1" + dup = cta._transcript_facts( + (*msgs, MappingProxyType({"role": "user", "turn_id": "t1", "message_id": "m2", "text": "x"})), + "t1", + ) + assert dup == {"count": 2} + + events = ( + MappingProxyType({"kind": "turn.queued", "payload": {"n": 1}}), + MappingProxyType({"kind": "turn.queued", "payload": {"n": 2}}), + ) + assert cta._queued_event_facts(events[:1])["count"] == 1 + assert cta._queued_event_facts(events) == {"count": 2} + + turns = ( + MappingProxyType({"turn_id": "done", "status": "completed", "_acceptance": {}}), + MappingProxyType({"turn_id": "p1", "client_turn_id": "c1", "status": "running", "_acceptance": {}}), + MappingProxyType({"turn_id": "p2", "client_turn_id": "c2", "status": "queued", "_acceptance": {}}), + ) + assert cta._prepared_turn_facts(turns[:2]) == { + "count": 1, + "turn_id": "p1", + "client_turn_id": "c1", + } + assert cta._prepared_turn_facts(turns) == {"count": 2} + + +def test_real_ts_round_trips_accept_mapping_proxy_inputs() -> None: + session_busy = MappingProxyType({"status": "busy", "active_turn_id": "t-act"}) + session_ready = MappingProxyType({"status": "ready", "active_turn_id": None}) + turn_queued = MappingProxyType( + { + "turn_id": "t-q", + "status": "queued", + "origin": "web", + "message": "orig", + "input_revision": 0, + "attachments": (MappingProxyType({"id": "a1"}),), + } + ) + turn_active = MappingProxyType({"turn_id": "t-act", "status": "running", "origin": "web"}) + + assert cta.queued_chat_turn_ids((turn_queued,), None) == ["t-q"] + mention = cta.plan_native_mention_ingress( + mentioned=True, + binding_matches=True, + text_only=True, + may_deliver_new=True, + target_turn_id="t-act", + queued_turn_exists=False, + receipt=None, + receipt_message_matches=False, + ) + assert isinstance(mention, dict) and "action" in mention + + steer_with_att = cta.plan_queued_chat_steering( + session_busy, + turn_queued, + turn_active, + None, + ingress_id="in-1", + operation_id="op-1", + target="t-act", + phase="prepare", + web_origin_only=True, + ) + assert steer_with_att == { + "action": "reject", + "error_code": "queue_steering_attachments_unavailable", + } + steer_text = cta.plan_queued_chat_steering( + session_busy, + MappingProxyType( + {"turn_id": "t-q", "status": "queued", "origin": "web", "message": "orig"} + ), + turn_active, + None, + ingress_id="in-1", + operation_id="op-1", + target="t-act", + phase="prepare", + web_origin_only=True, + ) + assert steer_text["action"] == "dispatch" + + edit_plan = cta.plan_queued_chat_mutation( + session_busy, + turn_queued, + MappingProxyType( + {"operation_id": "op1", "expected_revision": 0, "action": "edit", "message": "updated"} + ), + ) + assert edit_plan["action"] == "apply" + assert edit_plan["message_patch"]["text"] == "updated" + + conflict_plan = cta.plan_queued_chat_mutation( + session_busy, + turn_queued, + MappingProxyType({"operation_id": "op2", "expected_revision": 9, "action": "cancel"}), + ) + assert conflict_plan == {"action": "reject", "error_code": "queue_input_revision_conflict"} + + assert cta.managed_turn_execution_allowed(session_busy, turn_active) is True + assert cta.managed_turn_recovery_allowed( + session_busy, turn_active, managed=True, owner_dead=True + ) is True + + plan = cta.plan_managed_turn_acceptance( + session_id="s1", + client_turn_id="ct1", + message="hi", + display_message="", + attachments=(), + origin="web", + loopx_execution=False, + loopx_request=None, + candidate_turn_id="t1", + candidate_message_id="m1", + accepted_at="2026-11-26T00:00:00Z", + session=session_ready, + active_turn=None, + matching_turn=None, + turns=(), + messages=(), + queued_events=(), + ) + assert plan.disposition == "created" + assert plan.dispatch_required is True + + +def test_decode_rejection_errors_and_malformed_effect_results( + monkeypatch: pytest.MonkeyPatch, +) -> None: + for code, exc_type in ( + ("session_not_found", KeyError), + ("session_closed", KeyError), + ("request_conflict", cta.ManagedTurnReplayConflictError), + ("active_turn_conflict", RuntimeError), + ("original_request_unavailable", ValueError), + ("durable_state_conflict", cta.ManagedTurnReplayConflictError), + ("unsupported_code", ValueError), + ): + with pytest.raises(exc_type): + cta._decode_plan( + MappingProxyType( + { + "schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, + "kind": "rejected", + "code": code, + "active_turn_id": "t-act", + } + ) + ) + + valid_writes = { + "prepare_turn": True, + "activate_session": True, + "append_message": True, + "append_queued_event": True, + "settle_turn": False, + } + for bad in ( + "not_mapping", + {"schema_version": "wrong"}, + {"schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, "kind": "other"}, + { + "schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, + "kind": "accepted", + "disposition": "bad", + }, + { + "schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, + "kind": "accepted", + "disposition": "created", + "writes": "bad", + "dispatch": {"kind": "required"}, + }, + { + "schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, + "kind": "accepted", + "disposition": "created", + "writes": valid_writes, + "dispatch": {"kind": "required", "reason": "terminal"}, + }, + { + "schema_version": cta.CHAT_TURN_ACCEPTANCE_RESULT_SCHEMA, + "kind": "accepted", + "disposition": "replayed", + "writes": valid_writes, + "dispatch": {"kind": "not_required", "reason": "bad_reason"}, + }, + ): + with pytest.raises(ValueError): + cta._decode_plan(bad) + + monkeypatch.setattr(cta, "effect_runtime_result", lambda *_a, **_kw: {"turn_ids": [123]}) + with pytest.raises(ValueError, match="turn_ids"): + cta.queued_chat_turn_ids((), None) + + monkeypatch.setattr(cta, "effect_runtime_result", lambda *_a, **_kw: "bad") + with pytest.raises(ValueError, match="must be an object"): + cta.plan_native_mention_ingress(mentioned=True) + with pytest.raises(ValueError, match="must be an object"): + cta.managed_turn_execution_allowed(None, None) + + monkeypatch.setattr( + cta, + "effect_runtime_result", + lambda *_a, **_kw: {"action": "apply", "event": {"kind": "", "payload": {}}}, + ) + with pytest.raises(ValueError, match="event kind"): + cta.plan_queued_chat_mutation({}, {"turn_id": "t1", "status": "queued"}, {}) + + +def test_queued_steering_preserves_nonempty_and_rejects_malformed_attachments(tmp_path: Path) -> None: + session_busy: dict[str, object] = {"status": "busy", "active_turn_id": "t-act"} + turn_active: dict[str, object] = {"turn_id": "t-act", "status": "running", "origin": "web"} + empty_cases: tuple[object, ...] = (None, [], ()) + for empty in empty_cases: + plan = cta.plan_queued_chat_steering( + session_busy, + {"turn_id": "t-q", "status": "queued", "origin": "web", "attachments": empty}, + turn_active, + None, + ingress_id="in-empty", + operation_id="op-empty", + target="t-act", + phase="prepare", + web_origin_only=True, + ) + assert plan["action"] == "dispatch" + + for nonempty in ( + {"id": "a1"}, + MappingProxyType({"id": "a1"}), + "attachment.md", + b"bytes", + {"att"}, + ): + plan = cta.plan_queued_chat_steering( + session_busy, + {"turn_id": "t-q", "status": "queued", "origin": "web", "attachments": nonempty}, + turn_active, + None, + ingress_id="in-nonempty", + operation_id="op-nonempty", + target="t-act", + phase="prepare", + web_origin_only=True, + ) + assert plan == {"action": "reject", "error_code": "queue_steering_attachments_unavailable"} + + malformed_cases: tuple[object, ...] = ({}, "", b"", set(), memoryview(b""), False, True, 0, 1) + for malformed in malformed_cases: + with pytest.raises(ValueError, match="queued turn attachments"): + cta.plan_queued_chat_steering( + session_busy, + {"turn_id": "t-q", "status": "queued", "origin": "web", "attachments": malformed}, + turn_active, + None, + ingress_id="in-bad", + operation_id="op-bad", + target="t-act", + phase="prepare", + web_origin_only=True, + ) + + store = ChatSessionStore(tmp_path / "rt", startup_maintenance=False) + sess = store.create_session( + goal_id="g-1", agent_id="main", adapter_kind="fake", upstream_thread_id="th-1", host_surface="web" + ) + sid = str(sess["session_id"]) + active, _ = store.create_turn(sid, client_turn_id="act-1", message="active", origin="web") + active_path = store._turn_path(sid, str(active["turn_id"])) + active_raw = json.loads(active_path.read_text(encoding="utf-8")) + active_raw["status"] = "running" + active_path.write_text(json.dumps(active_raw), encoding="utf-8") + loaded_session = store.load_session(sid) + assert loaded_session is not None + loaded_active = store.load_turn(sid, str(active["turn_id"])) + assert loaded_active is not None + + for idx, persisted_att in enumerate(({"id": "persisted-obj"}, "persisted.txt")): + queued, _ = store.create_queued_turn( + sid, client_turn_id=f"q-{idx}", message="queued", origin="web" + ) + turn_path = store._turn_path(sid, str(queued["turn_id"])) + raw = json.loads(turn_path.read_text(encoding="utf-8")) + raw["attachments"] = persisted_att + turn_path.write_text(json.dumps(raw), encoding="utf-8") + loaded_turn = store.load_turn(sid, str(queued["turn_id"])) + assert loaded_turn is not None + decision = cta.plan_queued_chat_steering( + loaded_session, + loaded_turn, + loaded_active, + None, + ingress_id=f"in-fs-{idx}", + operation_id=f"op-fs-{idx}", + target=str(active["turn_id"]), + phase="prepare", + web_origin_only=True, + ) + assert decision == { + "action": "reject", + "error_code": "queue_steering_attachments_unavailable", + }