diff --git a/loopx/chat/todo_action_contracts.py b/loopx/chat/todo_action_contracts.py new file mode 100644 index 0000000000..b4f0822652 --- /dev/null +++ b/loopx/chat/todo_action_contracts.py @@ -0,0 +1,402 @@ +"""Typed contracts and pure boundary helpers for Chat Todo/Task actions.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from contextlib import AbstractContextManager +from pathlib import Path +from typing import NoReturn, Protocol, runtime_checkable + +from ..chat_store import TERMINAL_TURN_STATES +from .action_store_common import is_str_dict, require_str_dict + +CANONICAL_UPDATE_BASIS_SCHEMA_VERSION = "loopx_chat_canonical_update_basis_v0" +CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION = "loopx_chat_canonical_terminal_basis_v0" + +MONITOR_OUTCOME_BY_OPERATION: dict[str, str] = { + "pause": "monitor_paused", + "resume": "monitor_resumed", + "edit": "monitor_updated", + "stop": "monitor_stopped", +} + + +class ActionStoreProtocol(Protocol): + """Minimal persistence contract implemented by ChatActionStore.""" + + def apply( + self, + proposal_id: str, + *, + current_state_fingerprint: str, + receipt: Mapping[str, object], + ) -> dict[str, object]: ... + + def save_checkpoint( + self, + proposal_id: str, + *, + step: str, + receipt: Mapping[str, object], + ) -> dict[str, object]: ... + + def mark_failed( + self, + proposal_id: str, + *, + error_code: str, + message: str, + details: Mapping[str, object] | None = None, + ) -> dict[str, object]: ... + + +@runtime_checkable +class TodoTurnLoaderProtocol(Protocol): + """Read-only turn lookup interface for pending task execution checks.""" + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: ... + + +@runtime_checkable +class TodoSessionStoreProtocol(TodoTurnLoaderProtocol, Protocol): + """Session and client-turn lookup interface for task recovery.""" + + def load_session(self, session_id: str) -> dict[str, object] | None: ... + + def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, object] | None: ... + + def session_candidates( + self, + *, + goal_id: str | None, + agent_id: str, + channel_id: str | None = None, + ) -> Sequence[Mapping[str, object]]: ... + + +class TodoRuntimeControllerProtocol(Protocol): + """Runtime controller interface matching ChatActionService's host contract.""" + + def capabilities(self) -> Sequence[Mapping[str, object]]: ... + + def open_session( + self, + *, + goal_id: str, + goal_instance_id: str | None = None, + agent_id: str, + work_dir: Path, + objective: str, + mode: str, + session_id: str | None = None, + channel_id: str, + agent_goal_id: str, + managed_agent_id: str = ..., + ) -> tuple[dict[str, object], bool]: ... + + def submit_turn( + self, + *, + session_id: str, + client_turn_id: str, + message: str, + work_dir: Path, + objective: str, + display_message: str = ..., + ) -> tuple[dict[str, object], bool]: ... + + def resume_session_queue(self, *, session_id: str, work_dir: Path, objective: str) -> object: ... + + +@runtime_checkable +class GoalCommitSubmitController(Protocol): + """Extended runtime controller contract supporting transactional _goal_commit.""" + + def submit_turn( + self, + *, + session_id: str, + client_turn_id: str, + message: str, + work_dir: Path, + objective: str, + _goal_commit: Callable[[], AbstractContextManager[None]] | None = ..., + ) -> tuple[dict[str, object], bool]: ... + + +class TodoUpdateRunner(Protocol): + """Signature shared by todo, monitor, and gate mutation runners.""" + + def __call__( + self, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: ... + + +class ChatTodoActionHost(Protocol): + """Host capabilities required by ChatTodoActionMixin.""" + + @property + def store(self) -> ActionStoreProtocol: ... + + @property + def registry_path(self) -> Path: ... + + @property + def chat_store(self) -> TodoTurnLoaderProtocol | None: ... + + @property + def runtime_controller(self) -> TodoRuntimeControllerProtocol | None: ... + + @property + def runtime_root_override(self) -> str | None: ... + + def _goal_state_fingerprint(self, goal_id: str) -> str: ... + + def _agent_eligibility( + self, + agent_id: str, + *, + project: Path | None = None, + requires_tools: bool = True, + require_healthy: bool = True, + ) -> dict[str, object]: ... + + def _resolve_goal_agent( + self, + goal_id: str, + endpoint_id: str, + *, + goal: dict[str, object] | None = None, + ) -> str: ... + + def _turn_from_receipt(self, receipt: object) -> dict[str, object] | None: ... + + def _run_monitor_update( + self, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: ... + + +class TodoActionServiceSelf(ChatTodoActionHost, Protocol): + """Combined host and Todo mixin surface for internal method delegation.""" + + def _run_todo_update( + self, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: ... + + def _run_gate_resolve( + self, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: ... + + def _apply_reviewed_todo_edit( + self, + proposal_id: str, + proposal: Mapping[str, object], + parameters: dict[str, object], + ) -> dict[str, object]: ... + + +def raise_protected_action_gate( + action_kind: str, + *, + gate: Mapping[str, object], + cause: Exception | None = None, +) -> NoReturn: + """Raise ProtectedActionGate via lazy import to avoid module cycles.""" + from ..chat_actions import ProtectedActionGate + + error = ProtectedActionGate(action_kind, gate=gate) + if cause is not None: + raise error from cause + raise error + + +def decision_readback(result: Mapping[str, object]) -> dict[str, object]: + """Carry the canonical outcome and dependent effect, never a local guess.""" + resume = result.get("unblock_resume") + return { + "decision_outcome": result.get("decision_outcome"), + "unblock_resume_state": resume.get("state") if isinstance(resume, Mapping) else None, + } + + +def todo_checkpoints(proposal: Mapping[str, object]) -> dict[str, object]: + """Extract persisted step checkpoints from a proposal payload.""" + checkpoint = proposal.get("checkpoint") + steps = checkpoint.get("steps") if is_str_dict(checkpoint) else None + return steps if is_str_dict(steps) else {} + + +def parse_reviewed_terminal_options( + basis: Mapping[str, object] | None, + operation_id: str | None, +) -> tuple[str | None, dict[str, object] | None]: + """Validate and unpack reviewed terminal completion options.""" + if basis is None: + return None, None + if basis.get("schema_version") != CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION: + raise ValueError("unsupported canonical terminal review basis; regenerate preview") + return operation_id, { + "provider_revision": basis["provider_revision"], + "registry_sha256": basis["registry_sha256"], + } + + +def reviewed_terminal_options( + basis: Mapping[str, object] | None, + operation_id: str | None, +) -> dict[str, object]: + """Return kwargs mapping for complete_goal_todo calls.""" + completion_turn_key, terminal_review_basis = parse_reviewed_terminal_options(basis, operation_id) + if terminal_review_basis is None: + return {} + return { + "completion_turn_key": completion_turn_key, + "terminal_review_basis": terminal_review_basis, + } + + +def parse_reviewed_update_options( + basis: Mapping[str, object] | None, + operation_id: str | None, +) -> tuple[str | None, str | None, str | None]: + """Validate and unpack reviewed non-terminal update CAS options.""" + if basis is None: + return None, None, None + if basis.get("schema_version") != CANONICAL_UPDATE_BASIS_SCHEMA_VERSION: + raise ValueError("unsupported canonical update review basis; regenerate preview") + return ( + operation_id, + str(basis["provider_revision"]), + str(basis["registry_sha256"]), + ) + + +def reviewed_update_options( + basis: Mapping[str, object] | None, + operation_id: str | None, +) -> dict[str, object]: + """Return kwargs mapping for update_goal_todo calls.""" + update_op, provider_revision, registry_sha256 = parse_reviewed_update_options(basis, operation_id) + if provider_revision is None: + return {} + return { + "update_operation_id": update_op, + "update_expected_provider_revision": provider_revision, + "update_expected_registry_sha256": registry_sha256, + } + + +def task_turn_dispatched(turn: Mapping[str, object]) -> bool: + """Return whether a task Turn has already been dispatched or terminated.""" + return turn.get("status") in TERMINAL_TURN_STATES or bool( + turn.get("started_at") or turn.get("upstream_turn_id") + ) + + +def as_optional_str(value: object) -> str | None: + """Preserve None while normalizing non-None scalar inputs to str.""" + return None if value is None else str(value) + + +def as_optional_int(value: object, *, field: str) -> int | None: + """Validate optional integer parameter without accepting bool.""" + if value is None: + return None + if isinstance(value, int) and not isinstance(value, bool): + return value + raise ValueError(f"{field} must be an integer") + + +def as_optional_str_list(value: object, *, field: str) -> list[str] | None: + """Normalize optional string sequence parameter to a concrete list.""" + if value is None: + return None + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return [str(item) for item in value] + raise ValueError(f"{field} must be a sequence of strings") + + +def as_dict_list(value: object) -> list[dict[str, object]]: + """Filter a sequence payload into typed string-keyed row dictionaries.""" + if not isinstance(value, Sequence) or isinstance(value, (str, bytes)): + return [] + return [row for row in value if is_str_dict(row)] + + +def require_str(value: object, *, error: str) -> str: + """Require a non-empty string value or raise ValueError.""" + if not isinstance(value, str) or not value: + raise ValueError(error) + return value + + +def resolve_turn_loader( + controller: object, + chat_store: TodoTurnLoaderProtocol | None, +) -> TodoTurnLoaderProtocol | None: + """Resolve the active turn loader from controller.store or chat_store.""" + raw_store = getattr(controller, "store", None) + candidate = raw_store if raw_store is not None else chat_store + return candidate if isinstance(candidate, TodoTurnLoaderProtocol) else None + + +def resolve_session_store( + controller: object, + chat_store: TodoTurnLoaderProtocol | None, +) -> TodoSessionStoreProtocol | None: + """Resolve the full session store from controller.store or chat_store.""" + raw_store = getattr(controller, "store", None) + candidate = raw_store if raw_store is not None else chat_store + return candidate if isinstance(candidate, TodoSessionStoreProtocol) else None + + +__all__ = [ + "ActionStoreProtocol", + "CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION", + "CANONICAL_UPDATE_BASIS_SCHEMA_VERSION", + "ChatTodoActionHost", + "GoalCommitSubmitController", + "MONITOR_OUTCOME_BY_OPERATION", + "TodoActionServiceSelf", + "TodoRuntimeControllerProtocol", + "TodoSessionStoreProtocol", + "TodoTurnLoaderProtocol", + "TodoUpdateRunner", + "as_dict_list", + "as_optional_int", + "as_optional_str", + "as_optional_str_list", + "decision_readback", + "is_str_dict", + "parse_reviewed_terminal_options", + "parse_reviewed_update_options", + "raise_protected_action_gate", + "require_str", + "require_str_dict", + "resolve_session_store", + "resolve_turn_loader", + "reviewed_terminal_options", + "reviewed_update_options", + "task_turn_dispatched", + "todo_checkpoints", +] diff --git a/loopx/chat/todo_action_create.py b/loopx/chat/todo_action_create.py new file mode 100644 index 0000000000..20b38eb977 --- /dev/null +++ b/loopx/chat/todo_action_create.py @@ -0,0 +1,295 @@ +"""Todo creation, legacy recovery, and assignment execution helpers.""" + +from __future__ import annotations + +from collections.abc import Mapping + +from ..agent_registry import registered_agent_ids_for_goal +from ..chat import apply_todo_review_preview, build_todo_review_preview +from ..control_plane.coordination.local_authority import ( + LocalCoordinationAuthorityUnavailable, + read_canonical_todos_if_promoted, +) +from ..control_plane.todos.mutation_api import update_goal_todo +from .action_store_common import _opaque_id, is_str_dict, require_str_dict +from .todo_action_contracts import ( + ChatTodoActionHost, + as_optional_str, + raise_protected_action_gate, + task_turn_dispatched, + todo_checkpoints, +) +from .todo_action_tasks import ( + apply_created_todo_assignment, + read_confirmed_task, + start_confirmed_task, +) +from .todo_source import ChatTodoSource, ChatTodoSourceChanged, resolve_chat_todo_source + + +def _raise_legacy_todo_source_gate(todo_id: str, error: Exception) -> None: + summary = f"The original confirmation recorded Todo {todo_id}. Its assignment source could not be verified." + next_action = "Restore the original Goal source and retry, or review the assignment from the existing Todo." + current = error.verified_todo if isinstance(error, ChatTodoSourceChanged) else None + if current is not None: + assignee = current.get("claimed_by") + assignment_state = f"Its current assignee is {assignee}." if assignee else "It is currently unassigned." + summary = ( + f"The original confirmation created Todo {todo_id}. {assignment_state} " + "The original assignment could not be verified." + ) + next_action = "Open the existing Todo to review its current assignment." + raise_protected_action_gate( + "todo.create", + gate={"kind": "canonical_authority_required", "summary": summary, "next_action": next_action}, + cause=error, + ) + + +def _recover_legacy_todo_source( + host: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + *, + source: ChatTodoSource, + todo_step: Mapping[str, object], + steps: Mapping[str, object], + todo_id: str, + canonical_receipt: dict[str, object], + current_fingerprint: str, + agent_id: object, + start_execution: bool, + assignment_completed: bool, +) -> tuple[object, bool]: + goal_id = str(parameters["goal_id"]) + assignment = steps.get("todo_assigned") + if is_str_dict(assignment) and ( + not agent_id or assignment.get("todo_id") != todo_id or assignment.get("agent_id") != str(agent_id) + ): + raise ChatTodoSourceChanged("The saved assignment does not identify this Task and Agent.") + authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) + if start_execution and agent_id and authority: + # A committed claim can predate the corresponding Chat checkpoint. + claim_completed = source.has_managed_task_claim( + proposal_id, todo_id, str(agent_id), str(authority["source_authority"]), + ) + if assignment_completed and not claim_completed: + # Older releases submitted the Turn after a plain assignment. + _, turn = read_confirmed_task(host, proposal_id, parameters, todo_id, steps) + if turn is None or not task_turn_dispatched(turn): + raise ChatTodoSourceChanged("The saved Task start claim is unavailable.") + assignment_completed = assignment_completed or claim_completed + binding = source.recover_legacy_creation( + todo_id=todo_id, + preview_id=current_fingerprint, + receipt=canonical_receipt, + authority=authority, + assignment_pending=bool(agent_id) and not assignment_completed, + ) + if not assignment_completed and agent_id and agent_id not in registered_agent_ids_for_goal(source.goal): + raise ChatTodoSourceChanged("The selected Agent is no longer registered for the Goal") + return binding, assignment_completed + + +def _recover_created_todo_step( + host: ChatTodoActionHost, + proposal_id: str, + proposal: Mapping[str, object], + parameters: Mapping[str, object], + *, + source: ChatTodoSource, + todo_step: Mapping[str, object], + steps: Mapping[str, object], + agent_id: object, + start_execution: bool, + assignment_completed: bool, +) -> tuple[str, dict[str, object], dict[str, object], str, bool]: + todo_id = _opaque_id(todo_step.get("todo_id"), field="todo_id") + raw_canonical = todo_step.get("canonical_receipt") + if not is_str_dict(raw_canonical): + raise ValueError("Todo creation checkpoint is malformed") + canonical_receipt = raw_canonical + current_fingerprint = str(proposal.get("expected_state_fingerprint") or "") + binding_obj = todo_step.get("source") + if "source" not in todo_step: + try: + binding_obj, assignment_completed = _recover_legacy_todo_source( + host, + proposal_id, + parameters, + source=source, + todo_step=todo_step, + steps=steps, + todo_id=todo_id, + canonical_receipt=canonical_receipt, + current_fingerprint=current_fingerprint, + agent_id=agent_id, + start_execution=start_execution, + assignment_completed=assignment_completed, + ) + except (ChatTodoSourceChanged, LocalCoordinationAuthorityUnavailable) as error: + _raise_legacy_todo_source_gate(todo_id, error) + host.store.save_checkpoint(proposal_id, step="todo_created", receipt={**todo_step, "source": binding_obj}) + if not is_str_dict(binding_obj): + raise ValueError("Todo creation checkpoint source is malformed") + source.require_review(binding_obj) + return todo_id, canonical_receipt, binding_obj, current_fingerprint, assignment_completed + + +def _create_new_todo_step( + host: ChatTodoActionHost, + proposal_id: str, + proposal: Mapping[str, object], + parameters: Mapping[str, object], + *, + source: ChatTodoSource, + agent_id: object, +) -> tuple[str, dict[str, object], dict[str, object], str] | dict[str, object]: + goal_id = str(parameters["goal_id"]) + if agent_id and agent_id not in registered_agent_ids_for_goal(source.goal): + raise ValueError("the selected Agent is no longer registered for this Goal") + authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) + if not isinstance(authority.get("store_identity"), str): + raise ValueError("The Goal's Todo authority identity is unavailable") + priority = as_optional_str(parameters.get("priority")) + current = build_todo_review_preview( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + goal_id=goal_id, + text=str(parameters["text"]), + priority=priority, + source_identity=source.source_identity, + ) + current_fingerprint = str(current["preview_id"]) + if current_fingerprint != proposal.get("expected_state_fingerprint"): + stale = host.store.apply(proposal_id, current_state_fingerprint=current_fingerprint, receipt={}) + return {"proposal": stale, "turn": None} + applied = apply_todo_review_preview( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + goal_id=goal_id, + text=str(parameters["text"]), + priority=priority, + preview_id=current_fingerprint, + expected_registry_sha256=source.registry_sha256, + routing_registry_witness=source.routing_registry_witness, + source_identity=source.source_identity, + return_authority_write=True, + ) + canonical_receipt = require_str_dict(applied.get("receipt"), error="Todo review receipt is malformed") + authority_write = require_str_dict( + applied.get("authority_write"), + error="Todo authority write receipt is malformed", + ) + todo_id = _opaque_id(canonical_receipt["todo_id"], field="todo_id") + binding: dict[str, object] = { + **authority_write, + "source_identity": source.source_identity, + "store_identity": authority["store_identity"], + "registry_sha256": source.registry_sha256, + } + host.store.save_checkpoint( + proposal_id, + step="todo_created", + receipt={"todo_id": todo_id, "canonical_receipt": canonical_receipt, "source": binding}, + ) + return todo_id, canonical_receipt, binding, current_fingerprint + + +def _assign_created_todo( + host: ChatTodoActionHost, + proposal_id: str, + *, + goal_id: str, + todo_id: str, + agent_id: str, + binding: Mapping[str, object], + steps: Mapping[str, object], +) -> None: + def apply_assignment(current_source: ChatTodoSource, revision: str) -> dict[str, object]: + return update_goal_todo( + registry_path=current_source.registry_path, + runtime_root_arg=str(current_source.runtime_root), + goal_id=goal_id, + todo_id=todo_id, + claimed_by=agent_id, + agent_id=agent_id, + authority_reason="owner-confirmed typed Chat action", + update_operation_id=f"chat-assign:{proposal_id}", + update_expected_provider_revision=revision, + update_expected_registry_sha256=current_source.registry_sha256, + routing_registry_witness=current_source.routing_registry_witness, + dry_run=False, + ) + + apply_created_todo_assignment( + host, proposal_id, goal_id=goal_id, todo_id=todo_id, + binding=binding, steps=steps, apply_mutation=apply_assignment, + ) + host.store.save_checkpoint( + proposal_id, step="todo_assigned", receipt={"todo_id": todo_id, "agent_id": agent_id}, + ) + + +def apply_todo_create( + host: ChatTodoActionHost, + proposal_id: str, + proposal: Mapping[str, object], + parameters: Mapping[str, object], +) -> dict[str, object]: + """Create, assign, and optionally launch execution for a reviewed Todo.""" + goal_id = str(parameters["goal_id"]) + source = resolve_chat_todo_source(host, goal_id) + agent_id = parameters.get("agent_id") + start_execution = parameters.get("start_execution") is True + steps = todo_checkpoints(proposal) + assignment_completed = is_str_dict(steps.get("todo_assigned")) + todo_step = steps.get("todo_created") + if is_str_dict(todo_step) and todo_step.get("todo_id"): + todo_id, canonical_receipt, binding, current_fingerprint, assignment_completed = ( + _recover_created_todo_step( + host, proposal_id, proposal, parameters, source=source, todo_step=todo_step, + steps=steps, agent_id=agent_id, start_execution=start_execution, + assignment_completed=assignment_completed, + ) + ) + else: + created_or_stale = _create_new_todo_step( + host, proposal_id, proposal, parameters, source=source, agent_id=agent_id, + ) + if isinstance(created_or_stale, dict): + return created_or_stale + todo_id, canonical_receipt, binding, current_fingerprint = created_or_stale + + if agent_id and not start_execution and not assignment_completed: + _assign_created_todo( + host, proposal_id, goal_id=goal_id, todo_id=todo_id, + agent_id=str(agent_id), binding=binding, steps=steps, + ) + + resource_ids: dict[str, object] = { + "goal_id": str(canonical_receipt["goal_id"]), + "todo_id": todo_id, + **({"agent_id": str(agent_id)} if agent_id else {}), + } + receipt: dict[str, object] = { + "receipt_id": str(canonical_receipt["receipt_id"]), + "outcome": str(canonical_receipt["outcome"]), + "projection_verified": True, + "resource_ids": resource_ids, + "canonical_receipt": canonical_receipt, + } + turn_result: dict[str, object] | None = None + if start_execution: + source = resolve_chat_todo_source(host, goal_id) + source.require_review(binding) + turn_result = start_confirmed_task( + host, proposal_id, parameters, todo_id, steps, source=source, binding=binding, + ) + resource_ids.update({"session_id": turn_result["session_id"], "turn_id": turn_result["turn_id"]}) + receipt["outcome"] = "task_execution_started" + stored = host.store.apply(proposal_id, current_state_fingerprint=current_fingerprint, receipt=receipt) + return {"proposal": stored, "turn": turn_result} + + +__all__ = ["apply_todo_create"] diff --git a/loopx/chat/todo_action_tasks.py b/loopx/chat/todo_action_tasks.py new file mode 100644 index 0000000000..f1ed833e1f --- /dev/null +++ b/loopx/chat/todo_action_tasks.py @@ -0,0 +1,493 @@ +"""Task assignment, session admission, claim, and recovery workflows for Todo actions.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator, Mapping +from contextlib import ExitStack, contextmanager +from pathlib import Path + +from ..control_plane.coordination.local_authority import ( + LocalCoordinationAuthorityUnavailable, + read_canonical_todos_if_promoted, +) +from ..control_plane.coordination.shadow_management import shadow_maintenance_lock_target +from ..control_plane.goals.activation import goal_is_stopped +from ..control_plane.todos.mutation_api import update_goal_todo +from ..control_plane.work_items.task_lease import lease_is_active +from ..file_lock import exclusive_cross_runtime_file_lock +from .action_store_common import _opaque_id, is_str_dict, require_str_dict +from .todo_action_contracts import ( + ChatTodoActionHost, + GoalCommitSubmitController, + TodoSessionStoreProtocol, + as_dict_list, + require_str, + resolve_session_store, + resolve_turn_loader, + task_turn_dispatched, + todo_checkpoints, +) +from .todo_source import ( + ChatTodoSource, + ChatTodoSourceChanged, + resolve_chat_todo_source, + task_start_claim_operation_id, +) + + +def read_task_start( + chat: TodoSessionStoreProtocol, + *, + goal_id: str, + agent_id: str, + channel_id: str, + client_turn_id: str, + checkpoint: Mapping[str, object] | None, +) -> tuple[dict[str, object] | None, dict[str, object] | None]: + """Read the persisted Task Session and Turn for creation or recovery.""" + if checkpoint is not None: + sid = _opaque_id(checkpoint.get("session_id"), field="session_id") + session = chat.load_session(sid) + if ( + session is None + or session.get("goal_id") != goal_id + or session.get("agent_id") != agent_id + or session.get("channel_id") != channel_id + ): + raise ValueError("The original Task Session is unavailable") + return session, chat.turn_for_client(sid, client_turn_id) + + # A process may have persisted the Session before the proposal's + # checkpoint. Include closed Sessions so retry cannot replace one. + sessions = [ + dict(candidate) + for candidate in chat.session_candidates( + goal_id=goal_id, + agent_id=agent_id, + channel_id=channel_id, + ) + ] + matches: list[tuple[dict[str, object], dict[str, object]]] = [] + for session in sessions: + turn = chat.turn_for_client(str(session["session_id"]), client_turn_id) + if turn is not None: + matches.append((session, turn)) + if len(matches) == 1: + return matches[0] + if len(sessions) > 1: + raise ValueError("The original Task Session is ambiguous") + return (sessions[0] if sessions else None), None + + +def read_confirmed_task( + host: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + todo_id: str, + steps: Mapping[str, object], + *, + execution: Mapping[str, object] | None = None, +) -> tuple[dict[str, object] | None, dict[str, object] | None]: + """Load the confirmed Task Session and Turn matching the reviewed request.""" + chat = resolve_session_store(host.runtime_controller, host.chat_store) + if chat is None: + raise ValueError("Chat Runtime Controller is unavailable") + active_execution = execution if execution is not None else steps.get("execution_started") + execution_map = active_execution if isinstance(active_execution, Mapping) else None + opened = steps.get("task_session_opened") + checkpoint = execution_map if execution_map is not None else (opened if isinstance(opened, Mapping) else None) + session, turn = read_task_start( + chat, + goal_id=str(parameters["goal_id"]), + agent_id=str(parameters.get("endpoint_id") or parameters["agent_id"]), + channel_id=f"task.{todo_id}", + client_turn_id=f"task-start-{proposal_id}", + checkpoint=checkpoint, + ) + if execution_map is not None and (turn is None or turn.get("turn_id") != execution_map.get("turn_id")): + raise ValueError("The original Task Turn is unavailable") + if turn is not None and turn.get("message") != str(parameters["text"]): + raise ValueError("The original Task Turn request changed") + return session, turn + + +def pending_applied_task_receipt( + host: ChatTodoActionHost, + proposal: Mapping[str, object], +) -> dict[str, object] | None: + """Find the exact accepted Turn whose worker has yet to start.""" + raw_params = proposal.get("normalized_parameters") + parameters = raw_params if isinstance(raw_params, Mapping) else {} + raw_receipt = proposal.get("receipt") + receipt = raw_receipt if isinstance(raw_receipt, Mapping) else {} + raw_context = proposal.get("context") + context = raw_context if isinstance(raw_context, Mapping) else {} + if ( + proposal.get("status") != "applied" + or proposal.get("action_kind") != "todo.create" + or parameters.get("start_execution") is not True + or proposal.get("permission_classification") != "durable_write" + or context.get("binding_id") + or receipt.get("outcome") != "task_execution_started" + or receipt.get("projection_verified") is not True + ): + return None + resources = receipt.get("resource_ids") + canonical = receipt.get("canonical_receipt") + if not is_str_dict(resources) or not is_str_dict(canonical): + return None + goal_id = parameters.get("goal_id") + todo_id = resources.get("todo_id") + sid = resources.get("session_id") + tid = resources.get("turn_id") + if ( + not isinstance(goal_id, str) or not goal_id + or not isinstance(todo_id, str) or not todo_id + or not isinstance(sid, str) or not sid + or not isinstance(tid, str) or not tid + or resources.get("goal_id") != goal_id + or canonical.get("goal_id") != goal_id + or canonical.get("todo_id") != todo_id + or canonical.get("status") != "applied" + or canonical.get("preview_id") != proposal.get("expected_state_fingerprint") + ): + return None + chat = resolve_turn_loader(host.runtime_controller, host.chat_store) + if chat is None: + return None + try: + turn = chat.load_turn(sid, tid) + except (OSError, ValueError): + return None + if ( + turn + and turn.get("session_id") == sid + and turn.get("turn_id") == tid + and turn.get("client_turn_id") == f"task-start-{proposal['proposal_id']}" + and turn.get("status") == "queued" + and not (turn.get("started_at") or turn.get("upstream_turn_id")) + ): + return resources + return None + + +def project_task_dispatch( + host: ChatTodoActionHost, + proposal: Mapping[str, object], +) -> dict[str, object]: + """Annotate an applied task proposal when its queued Turn awaits worker dispatch.""" + base = dict(proposal) + if pending_applied_task_receipt(host, proposal) is not None: + return {**base, "task_execution_dispatch_pending": True} + return base + + +def apply_created_todo_assignment( + host: ChatTodoActionHost, + proposal_id: str, + *, + goal_id: str, + todo_id: str, + binding: Mapping[str, object], + steps: Mapping[str, object], + apply_mutation: Callable[[ChatTodoSource, str], dict[str, object]], +) -> dict[str, object]: + """Assign or claim a newly created Todo with CAS basis recovery.""" + binding_dict = dict(binding) + + def observe() -> tuple[ChatTodoSource, dict[str, object]]: + source = resolve_chat_todo_source(host, goal_id) + source.require_review(binding_dict) + authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) + source.require_created_todo(binding_dict, authority) + return source, authority + + source, _ = observe() + raw_basis = steps.get("todo_assignment_basis", binding_dict) + basis_dict = require_str_dict(raw_basis, error="Todo assignment basis is malformed") + revision = str(basis_dict["provider_revision"]) + try: + return apply_mutation(source, revision) + except LocalCoordinationAuthorityUnavailable as error: + if error.code != "provider_revision_mismatch": + raise + + # Only a definitive stale-revision rejection permits a new CAS basis. + # Preserve it before dispatch so a lost response replays the same intent. + source, authority = observe() + current_revision = source.current_assignment_revision(binding_dict, authority, todo_id) + host.store.save_checkpoint( + proposal_id, + step="todo_assignment_basis", + receipt={"provider_revision": current_revision}, + ) + return apply_mutation(source, current_revision) + + +@contextmanager +def confirmed_task_commit( + host: ChatTodoActionHost, + *, + goal_id: str, + todo_id: str, + endpoint: str, + project: Path, + claim: Mapping[str, object], + source: ChatTodoSource, + binding: Mapping[str, object], +) -> Iterator[None]: + """Fence acceptance with the same registry and canonical writers as Stop and Todo edits.""" + invoked = host.registry_path.resolve() + runtime = source.runtime_root + targets: tuple[Path, ...] = (shadow_maintenance_lock_target(runtime, goal_id), source.registry_path) + if source.registry_path != invoked: + targets += (invoked,) + binding_dict = dict(binding) + with ExitStack() as locks: + for target in targets: + locks.enter_context(exclusive_cross_runtime_file_lock(target, operation="confirm_task_admission")) + current_source = resolve_chat_todo_source(host, goal_id) + current_source.require_review(binding_dict) + goal = current_source.goal + if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal): + raise ValueError("The Task's Goal is no longer active") + if Path(str(goal.get("repo") or ".")).expanduser().resolve() != project: + raise ValueError("The reviewed Task's project root changed") + owner = claim["claimed_by"] + if host._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner: + raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent") + authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id, include_leases=True) + current_source.require_created_todo(binding_dict, authority) + todo = next((row for row in as_dict_list(authority.get("todos")) if row.get("todo_id") == todo_id), None) + if ( + todo is None or todo.get("role") != "agent" or todo.get("status") != "open" + or todo.get("claimed_by") != owner or authority.get("handoff_mode") != claim.get("handoff_mode") + ): + raise ValueError("The reviewed Task assignment changed before launch") + if authority.get("handoff_mode") == "hard_lease": + lease = next((row for row in as_dict_list(authority.get("leases")) if row.get("todo_id") == todo_id), None) + original = claim.get("lease") + if ( + not lease or not is_str_dict(original) or not lease_is_active(lease) + or any(lease.get(key) != original.get(key) for key in ("owner", "idempotency_key", "lease_epoch")) + ): + raise ValueError("The reviewed Task execution lease changed before launch") + yield + + +def _claim_task_for_dispatch( + host: ChatTodoActionHost, + proposal_id: str, + *, + goal_id: str, + todo_id: str, + owner: str, + source: ChatTodoSource, + binding: Mapping[str, object], + steps: Mapping[str, object], + applied_execution: Mapping[str, object] | None, +) -> dict[str, object]: + def apply_claim(current_source: ChatTodoSource, revision: str) -> dict[str, object]: + return update_goal_todo( + registry_path=current_source.registry_path, + runtime_root_arg=str(current_source.runtime_root), + goal_id=goal_id, + todo_id=todo_id, + claimed_by=owner, + agent_id=owner, + claim_only=True, + manage_execution=True, + claim_operation_id=task_start_claim_operation_id(proposal_id), + dry_run=False, + claim_expected_provider_revision=revision, + claim_expected_registry_sha256=current_source.registry_sha256, + routing_registry_witness=current_source.routing_registry_witness, + ) + + if applied_execution is None: + claim = apply_created_todo_assignment( + host, proposal_id, goal_id=goal_id, todo_id=todo_id, + binding=binding, steps=steps, apply_mutation=apply_claim, + ) + else: + # Replay the accepted claim using the same intent. A stale + # basis cannot authorize another claim on an applied card. + basis_dict = require_str_dict(steps.get("todo_assignment_basis", binding), error="Todo assignment basis is malformed") + claim = apply_claim(source, str(basis_dict["provider_revision"])) + if claim.get("handoff_mode") == "soft_claim" and claim.get("status") in {"recovered", "replayed"}: + readback = update_goal_todo( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + goal_id=goal_id, + todo_id=todo_id, + claimed_by=owner, + agent_id=owner, + claim_only=True, + manage_execution=True, + dry_run=True, + ) + if readback.get("changed"): + raise ValueError("The reviewed Task assignment changed before launch") + if applied_execution is None and not is_str_dict(steps.get("todo_assigned")): + host.store.save_checkpoint( + proposal_id, step="todo_assigned", receipt={"todo_id": todo_id, "agent_id": owner}, + ) + return claim + + +def _dispatch_confirmed_task_turn( + host: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + todo_id: str, + steps: Mapping[str, object], + *, + source: ChatTodoSource, + binding: Mapping[str, object], + session: dict[str, object] | None, + opened: object, + execution: Mapping[str, object] | None, + applied_execution: Mapping[str, object] | None, +) -> tuple[dict[str, object], bool]: + controller = host.runtime_controller + if controller is None: + raise ValueError("Chat Runtime Controller is unavailable") + if session is not None and session.get("status") == "closed": + raise ValueError("The original Task Session is closed") + goal_id = str(parameters["goal_id"]) + owner = str(parameters["agent_id"]) + endpoint = str(parameters.get("endpoint_id") or owner) + message = str(parameters["text"]) + goal = source.goal + if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal): + raise ValueError("The Task's Goal is no longer active") + project = Path(str(goal.get("repo") or ".")).expanduser().resolve() + if not project.is_dir(): + raise ValueError("the Goal project root is unavailable") + host._agent_eligibility(endpoint, project=project) + if parameters.get("endpoint_id") and host._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner: + raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent") + claim = _claim_task_for_dispatch( + host, proposal_id, goal_id=goal_id, todo_id=todo_id, owner=owner, + source=source, binding=binding, steps=steps, applied_execution=applied_execution, + ) + active_session = session + if active_session is None: + active_session, _ = controller.open_session( + goal_id=goal_id, agent_id=endpoint, work_dir=project, objective=message, + mode="resume_latest", channel_id=f"task.{todo_id}", agent_goal_id=goal_id, + ) + sid = _opaque_id(active_session.get("session_id"), field="session_id") + if opened is None and execution is None: + host.store.save_checkpoint(proposal_id, step="task_session_opened", receipt={"session_id": sid}) + if not isinstance(controller, GoalCommitSubmitController): + raise ValueError("Chat Runtime Controller is unavailable") + return controller.submit_turn( + session_id=sid, + client_turn_id=f"task-start-{proposal_id}", + message=message, + work_dir=project, + objective=message, + _goal_commit=lambda: confirmed_task_commit( + host, goal_id=goal_id, todo_id=todo_id, endpoint=endpoint, + project=project, claim=claim, source=source, binding=binding, + ), + ) + + +def start_confirmed_task( + host: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + todo_id: str, + steps: Mapping[str, object], + *, + source: ChatTodoSource, + binding: Mapping[str, object], + applied_execution: Mapping[str, object] | None = None, +) -> dict[str, object]: + """Claim an accepted Todo, open its Session, and submit or replay its execution Turn.""" + opened = steps.get("task_session_opened") + raw_exec = applied_execution if applied_execution is not None else steps.get("execution_started") + execution = raw_exec if isinstance(raw_exec, Mapping) else None + session, turn = read_confirmed_task(host, proposal_id, parameters, todo_id, steps, execution=execution) + + # An already dispatched or terminal Turn is readback. Only work that + # still needs dispatch passes through the current Goal and claim gates. + if turn is not None and task_turn_dispatched(turn): + active_turn, created = turn, False + else: + active_turn, created = _dispatch_confirmed_task_turn( + host, proposal_id, parameters, todo_id, steps, source=source, binding=binding, + session=session, opened=opened, execution=execution, applied_execution=applied_execution, + ) + + identity: dict[str, object] = { + "session_id": _opaque_id(active_turn.get("session_id"), field="session_id"), + "turn_id": _opaque_id(active_turn.get("turn_id"), field="turn_id"), + } + if execution is None: + host.store.save_checkpoint(proposal_id, step="execution_started", receipt=identity) + return {**identity, "status": str(active_turn.get("status") or "accepted"), "created": created} + + +def recover_applied_task( + host: ChatTodoActionHost, + proposal: Mapping[str, object], +) -> dict[str, object] | None: + """Resume execution dispatch for an already applied task proposal.""" + execution = pending_applied_task_receipt(host, proposal) + if execution is None: + return host._turn_from_receipt(proposal.get("receipt")) + + parameters = require_str_dict(proposal.get("normalized_parameters"), error="typed Chat action proposal is malformed") + goal_id = require_str(parameters.get("goal_id"), error="goal_id is missing from applied task") + todo_id = require_str(execution.get("todo_id"), error="todo_id is missing from execution receipt") + agent_id = require_str(parameters.get("agent_id"), error="agent_id is missing from applied task") + source = resolve_chat_todo_source(host, goal_id) + steps = todo_checkpoints(proposal) + raw_created = steps.get("todo_created", {}) + raw_receipt = require_str_dict(proposal.get("receipt"), error="Todo execution receipt is malformed") + canonical = require_str_dict( + raw_receipt.get("canonical_receipt"), + error="The accepted Task's creation checkpoint changed", + ) + if not is_str_dict(raw_created) or ( + raw_created and (raw_created.get("todo_id") != todo_id or raw_created.get("canonical_receipt") != canonical) + ): + raise ValueError("The accepted Task's creation checkpoint changed") + authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) + if "source" in raw_created: + raw_binding = raw_created["source"] + if not is_str_dict(raw_binding): + raise ValueError("Todo creation checkpoint source is malformed") + binding = raw_binding + else: + binding = source.recover_legacy_creation( + todo_id=todo_id, + preview_id=str(proposal.get("expected_state_fingerprint") or ""), + receipt=canonical, + authority=authority, + assignment_pending=False, + ) + source.require_created_todo(binding, authority) + if not source.has_managed_task_claim( + str(proposal["proposal_id"]), todo_id, agent_id, str(authority["source_authority"]), + ): + raise ChatTodoSourceChanged("The saved Task start claim is unavailable.") + return start_confirmed_task( + host, str(proposal["proposal_id"]), parameters, todo_id, steps, + source=source, binding=binding, applied_execution=execution, + ) + + +__all__ = [ + "apply_created_todo_assignment", + "confirmed_task_commit", + "pending_applied_task_receipt", + "project_task_dispatch", + "read_confirmed_task", + "read_task_start", + "recover_applied_task", + "start_confirmed_task", +] diff --git a/loopx/chat/todo_action_updates.py b/loopx/chat/todo_action_updates.py new file mode 100644 index 0000000000..19b2e75226 --- /dev/null +++ b/loopx/chat/todo_action_updates.py @@ -0,0 +1,401 @@ +"""Reviewed and legacy Todo, Monitor, and Gate update execution helpers.""" + +from __future__ import annotations + +from collections.abc import Mapping + +from ..control_plane.coordination.local_authority import ( + LocalCoordinationAuthorityUnavailable, + read_canonical_todos_if_promoted, +) +from ..control_plane.todos.completion_validation import COMPLETION_VALIDATION_IN_PROGRESS +from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo +from ..control_plane.todos.provider_projection import projection_delivery_requires_ack +from .action_store_common import ActionConflictError, _canonical_digest, _opaque_id, is_str_dict, require_str_dict +from .todo_action_contracts import ( + CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION, + CANONICAL_UPDATE_BASIS_SCHEMA_VERSION, + MONITOR_OUTCOME_BY_OPERATION, + ChatTodoActionHost, + TodoActionServiceSelf, + TodoUpdateRunner, + as_dict_list, + as_optional_int, + as_optional_str, + as_optional_str_list, + decision_readback, + parse_reviewed_terminal_options, + parse_reviewed_update_options, +) +from .todo_source import ChatTodoSource, ChatTodoSourceChanged, resolve_chat_todo_source + + +def _dispatch_todo_update_mutation( + source: ChatTodoSource, + parameters: Mapping[str, object], + *, + goal_id: str, + operation: str, + basis: Mapping[str, object] | None, + operation_id: str | None, + dry_run: bool, + agent_id: str | None, + note: str | None, + successors: list[str] | None, + lease_key: str | None, + lease_version: int | None, +) -> dict[str, object]: + status = as_optional_str(parameters.get("status")) + if operation == "complete": + status = "done" + elif operation == "block": + status = "blocked" + elif operation == "defer": + status = "deferred" + update_op, update_rev, update_sha = parse_reviewed_update_options(basis, operation_id) + reason = ( + (note or "Owner requested deferral") + if operation in {"block", "defer"} + else ((note or "Owner explicitly requested task resumption") if status == "open" else None) + ) + return update_goal_todo( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + routing_registry_witness=source.routing_registry_witness, + goal_id=goal_id, + todo_id=str(parameters["todo_id"]), + text=as_optional_str(parameters.get("text")), + priority=as_optional_str(parameters.get("priority")), + clear_priority=bool( + parameters.get("clear_priority", False) or ("priority" in parameters and parameters["priority"] is None) + ), + status=status, + role="user" if operation == "complete" else None, + no_followup=bool(parameters.get("no_followup", True)) if operation == "complete" else None, + # The established block control uses note as its pause reason; + # preserve the task's existing notes. Explicit ordinary note edits + # and lifecycle effects still share the canonical transaction. + note=(note if operation != "block" or basis is None else None), + reason=reason, + claimed_by=(agent_id if operation == "reassign" else None), + resume_when=as_optional_str(parameters.get("resume_when")), + clear_resume_when=( + (operation == "block" or (status == "open" and not parameters.get("resume_when"))) + and basis is not None + ), + successor_todo_ids=successors, + agent_id=agent_id, + authority_reason="owner-confirmed typed Chat action", + dry_run=dry_run, + task_lease_idempotency_key=lease_key, + task_lease_expected_version=lease_version, + update_operation_id=update_op, + update_expected_provider_revision=update_rev, + update_expected_registry_sha256=update_sha, + ) + + +def run_todo_update( + host: ChatTodoActionHost, + parameters: Mapping[str, object], + *, + dry_run: bool, + basis: Mapping[str, object] | None = None, + operation_id: str | None = None, +) -> dict[str, object]: + """Validate and execute canonical Todo mutations (edit or terminal complete).""" + goal_id = str(parameters["goal_id"]) + operation = str(parameters.get("operation") or "edit") + reviewed = parameters.get("review_basis") + if dry_run and isinstance(reviewed, Mapping) and ( + basis is None or any(basis.get(key) != value for key, value in reviewed.items()) + ): + raise ValueError("The Task source changed. Reload its complete requirements before saving.") + source = resolve_chat_todo_source(host, goal_id) + if basis is not None: + source.require_review(dict(basis)) + # Transport only caller-supplied proof. The terminal owner revalidates + # the execution; a lease read or a Todo claim is never substitute proof. + lease_key = ( + as_optional_str(parameters.get("task_lease_idempotency_key")) + if operation == "complete" and "task_lease_idempotency_key" in parameters + else None + ) + lease_version = ( + as_optional_int(parameters.get("task_lease_expected_version"), field="task_lease_expected_version") + if operation == "complete" and "task_lease_expected_version" in parameters + else None + ) + successors = as_optional_str_list(parameters.get("successor_todo_ids"), field="successor_todo_ids") + agent_id = as_optional_str(parameters.get("agent_id")) + note = as_optional_str(parameters.get("note")) + if operation == "complete" and ( + basis is None or basis.get("schema_version") == CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION + ): + completion_turn_key, terminal_review_basis = parse_reviewed_terminal_options(basis, operation_id) + return complete_goal_todo( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + routing_registry_witness=source.routing_registry_witness, + goal_id=goal_id, + todo_id=str(parameters["todo_id"]), + note=note, + no_followup=bool(parameters.get("no_followup", True)), + successor_todo_ids=successors, + agent_id=agent_id, + authority_reason="owner-confirmed typed Chat action", + dry_run=dry_run, + task_lease_idempotency_key=lease_key, + task_lease_expected_version=lease_version, + completion_turn_key=completion_turn_key, + terminal_review_basis=terminal_review_basis, + ) + return _dispatch_todo_update_mutation( + source, parameters, goal_id=goal_id, operation=operation, basis=basis, + operation_id=operation_id, dry_run=dry_run, agent_id=agent_id, note=note, + successors=successors, lease_key=lease_key, lease_version=lease_version, + ) + + +def run_gate_resolve( + host: ChatTodoActionHost, + parameters: Mapping[str, object], + *, + dry_run: bool, + basis: Mapping[str, object] | None = None, + operation_id: str | None = None, +) -> dict[str, object]: + """Validate and record a User gate resolution via the terminal owner.""" + goal_id = str(parameters["goal_id"]) + source = resolve_chat_todo_source(host, goal_id) + if basis is not None: + source.require_review(dict(basis)) + completion_turn_key, terminal_review_basis = parse_reviewed_terminal_options(basis, operation_id) + return complete_goal_todo( + registry_path=source.registry_path, + runtime_root_arg=str(source.runtime_root), + routing_registry_witness=source.routing_registry_witness, + goal_id=goal_id, + todo_id=str(parameters["todo_id"]), + role="user", + decision_outcome=str(parameters["decision"]), + evidence=as_optional_str(parameters.get("note")), + no_followup=True, + agent_id=as_optional_str(parameters.get("agent_id")), + authority_reason="owner-confirmed typed Chat decision", + dry_run=dry_run, + completion_turn_key=completion_turn_key, + terminal_review_basis=terminal_review_basis, + ) + + +def canonical_update_basis( + host: ChatTodoActionHost, + goal_id: str, + *, + completion_todo_id: str | None = None, + decision: bool = False, +) -> dict[str, object] | None: + """Snapshot canonical authority identity and revision with TOCTOU verification.""" + source = resolve_chat_todo_source(host, goal_id) + authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) + current = resolve_chat_todo_source(host, goal_id) + if (current.source_identity, current.registry_sha256) != (source.source_identity, source.registry_sha256): + raise ValueError("Todo authority registration changed while reading; retry") + if authority is None: + return None + terminal = decision or ( + completion_todo_id is not None + and not any( + todo.get("todo_id") == completion_todo_id and todo.get("role") == "user" + for todo in as_dict_list(authority.get("todos")) + ) + ) + return { + "schema_version": ( + CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION if terminal else CANONICAL_UPDATE_BASIS_SCHEMA_VERSION + ), + "provider_revision": authority["provider_revision"], + "source_authority": authority["source_authority"], + "registry_sha256": source.registry_sha256, + "source_identity": source.source_identity, + } + + +def _handle_reviewed_edit_error( + host: ChatTodoActionHost, + proposal_id: str, + proposal: Mapping[str, object], + operation_id: str, + error: LocalCoordinationAuthorityUnavailable, + *, + terminal: bool, +) -> dict[str, object]: + if error.code == COMPLETION_VALIDATION_IN_PROGRESS: + raise ActionConflictError(str(error)) from error + if ( + terminal + and error.code == "authority_source_changed" + and error.payload.get("completion_validation_executed") is True + ): + host.store.mark_failed( + proposal_id, + error_code="canonical_update_validation_source_changed", + message="Todo authority registration changed during completion validation; retry", + details={"operation_id": operation_id, "reason_code": error.code}, + ) + raise ValueError("Todo authority registration changed during completion validation; retry") from error + if error.code in {"provider_revision_mismatch", "authority_source_changed", "provider_revision_conflict"}: + stale = host.store.apply( + proposal_id, + current_state_fingerprint=_canonical_digest( + {"expected": proposal["expected_state_fingerprint"], "conflict": error.code} + ), + receipt={}, + ) + return {"proposal": stale, "turn": None} + failed = host.store.mark_failed( + proposal_id, + error_code="canonical_update_retry_required", + message="The edit is not yet verified. Retry this proposal to recover the original operation.", + details={"operation_id": operation_id, "reason_code": error.code}, + ) + return {"proposal": failed, "turn": None} + + +def _reviewed_edit_outcome(action_kind: str, operation: str, *, changed: bool) -> str: + if action_kind == "gate.resolve": + return "gate_resolved" + if action_kind == "monitor.update": + return MONITOR_OUTCOME_BY_OPERATION[operation] + if operation == "complete": + return "todo_completed" + return "todo_updated" if changed else "todo_unchanged" + + +def apply_reviewed_todo_edit( + host: TodoActionServiceSelf, + proposal_id: str, + proposal: Mapping[str, object], + parameters: dict[str, object], +) -> dict[str, object]: + """Recover or execute a canonical update bound to a reviewed basis.""" + operation_id = f"chat-update:{proposal_id}" + raw_basis = proposal.get("canonical_update_basis") + basis = ( + require_str_dict(raw_basis, error="canonical update review basis is malformed") + if raw_basis is not None + else None + ) + action_kind = str(proposal["action_kind"]) + run: TodoUpdateRunner = ( + host._run_monitor_update + if action_kind == "monitor.update" + else host._run_gate_resolve + if action_kind == "gate.resolve" + else host._run_todo_update + ) + terminal = action_kind == "gate.resolve" or parameters.get("operation") in {"complete", "stop"} + try: + result = run(parameters, dry_run=False, basis=basis, operation_id=operation_id) + except ChatTodoSourceChanged as error: + failed = host.store.mark_failed( + proposal_id, error_code="canonical_update_source_changed", message=str(error), + details={"operation_id": operation_id}, + ) + return {"proposal": failed, "turn": None} + except LocalCoordinationAuthorityUnavailable as error: + return _handle_reviewed_edit_error(host, proposal_id, proposal, operation_id, error, terminal=terminal) + if result.get("ok") is not True: + failed = host.store.mark_failed( + proposal_id, + error_code="canonical_update_validation_failed", + message=( + "Completion validation did not pass. " + "The Todo was not completed; retry after resolving the validation failure." + ), + details={"operation_id": operation_id, "reason_code": result.get("reason_code")}, + ) + return {"proposal": failed, "turn": None} + raw_original = result.get("original_receipt") + original: Mapping[str, object] = raw_original if is_str_dict(raw_original) and raw_original else result + todo_id = _opaque_id(result.get("todo_id"), field="todo_id") + host.store.save_checkpoint( + proposal_id, + step="canonical_update", + receipt={"operation_id": operation_id, "todo_id": todo_id, "changed": original.get("changed") is True}, + ) + if not projection_delivery_requires_ack(result.get("projection_delivery")): + failed = host.store.mark_failed( + proposal_id, + error_code="canonical_update_projection_pending", + message=( + "The edit was committed. Display delivery is pending; " + "retry this proposal to restore the current view." + ), + details={"operation_id": operation_id, "canonical_committed": True}, + ) + return {"proposal": failed, "turn": None} + operation = str(parameters.get("operation", "edit")) + receipt: dict[str, object] = { + "receipt_id": _canonical_digest({"proposal_id": proposal_id, "todo_id": todo_id})[:32], + "outcome": _reviewed_edit_outcome(action_kind, operation, changed=bool(original.get("changed"))), + "projection_verified": True, + "projection_delivery": result["projection_delivery"], + "operation_id": operation_id, + "canonical_status": result.get("provider_status", result.get("status")), + "resource_ids": {"goal_id": str(parameters["goal_id"]), "todo_id": todo_id}, + } + if action_kind == "gate.resolve": + receipt.update(decision_readback(result)) + stored = host.store.apply( + proposal_id, + current_state_fingerprint=str(proposal["expected_state_fingerprint"]), + receipt=receipt, + ) + return {"proposal": stored, "turn": None} + + +def apply_todo_update( + host: TodoActionServiceSelf, + proposal_id: str, + proposal: Mapping[str, object], + parameters: dict[str, object], +) -> dict[str, object]: + """Execute either a canonical-basis-reviewed update or legacy fingerprint update.""" + if proposal.get("canonical_update_basis") is not None: + return host._apply_reviewed_todo_edit(proposal_id, proposal, parameters) + goal_id = str(parameters["goal_id"]) + current_fingerprint = host._goal_state_fingerprint(goal_id) + if current_fingerprint != proposal.get("expected_state_fingerprint"): + stale = host.store.apply(proposal_id, current_state_fingerprint=current_fingerprint, receipt={}) + return {"proposal": stale, "turn": None} + operation = str(parameters.get("operation") or "edit") + decision = proposal.get("action_kind") == "gate.resolve" + result = (host._run_gate_resolve if decision else host._run_todo_update)(parameters, dry_run=False) + todo_id = _opaque_id(result.get("todo_id"), field="todo_id") + receipt: dict[str, object] = { + "receipt_id": _canonical_digest({"proposal_id": proposal_id, "todo_id": todo_id})[:32], + "outcome": ( + "gate_resolved" + if decision + else "todo_completed" + if operation == "complete" + else ("todo_updated" if result.get("changed") else "todo_unchanged") + ), + "projection_verified": True, + "resource_ids": {"goal_id": goal_id, "todo_id": todo_id}, + } + if decision: + receipt.update(decision_readback(result)) + stored = host.store.apply(proposal_id, current_state_fingerprint=current_fingerprint, receipt=receipt) + return {"proposal": stored, "turn": None} + + +__all__ = [ + "apply_reviewed_todo_edit", + "apply_todo_update", + "canonical_update_basis", + "run_gate_resolve", + "run_todo_update", +] diff --git a/loopx/chat/todo_actions.py b/loopx/chat/todo_actions.py index 37582c3dd0..0ee805dac5 100644 --- a/loopx/chat/todo_actions.py +++ b/loopx/chat/todo_actions.py @@ -2,769 +2,242 @@ from __future__ import annotations -from collections.abc import Callable, Iterator -from contextlib import ExitStack, contextmanager +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager from pathlib import Path -from typing import Any -from ..agent_registry import registered_agent_ids_for_goal -from ..chat import apply_todo_review_preview, build_todo_review_preview -from ..chat_store import ChatSessionStore, TERMINAL_TURN_STATES -from ..file_lock import exclusive_cross_runtime_file_lock -from ..control_plane.goals.activation import goal_is_stopped -from ..control_plane.coordination.shadow_management import shadow_maintenance_lock_target -from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo -from ..control_plane.todos.completion_validation import COMPLETION_VALIDATION_IN_PROGRESS -from ..control_plane.coordination.local_authority import ( - LocalCoordinationAuthorityUnavailable, read_canonical_todos_if_promoted, +from .todo_action_contracts import ( + ChatTodoActionHost, + TodoActionServiceSelf, + TodoSessionStoreProtocol, + decision_readback, + reviewed_terminal_options, + reviewed_update_options, + task_turn_dispatched, + todo_checkpoints, ) -from ..control_plane.todos.provider_projection import projection_delivery_requires_ack -from ..control_plane.work_items.task_lease import lease_is_active -from .todo_source import ChatTodoSource, ChatTodoSourceChanged, resolve_chat_todo_source, task_start_claim_operation_id +from .todo_action_create import apply_todo_create +from .todo_action_tasks import ( + apply_created_todo_assignment, + confirmed_task_commit, + pending_applied_task_receipt, + project_task_dispatch as project_task_dispatch_record, + read_confirmed_task, + read_task_start, + recover_applied_task, + start_confirmed_task, +) +from .todo_action_updates import ( + apply_reviewed_todo_edit, + apply_todo_update, + canonical_update_basis, + run_gate_resolve, + run_todo_update, +) +from .todo_source import ChatTodoSource -def _decision_readback(result: dict[str, Any]) -> dict[str, Any]: +def _decision_readback(result: Mapping[str, object]) -> dict[str, object]: """Carry the canonical outcome and dependent effect, never a local guess.""" - resume = result.get("unblock_resume") - return { - "decision_outcome": result.get("decision_outcome"), - "unblock_resume_state": resume.get("state") if isinstance(resume, dict) else None, - } + return decision_readback(result) class ChatTodoActionMixin: """Keep Todo preview/apply parity separate from general orchestration.""" @staticmethod - def _todo_checkpoints(proposal: dict[str, Any]) -> dict[str, Any]: - checkpoint = proposal.get("checkpoint") - steps = checkpoint.get("steps") if isinstance(checkpoint, dict) else None - return steps if isinstance(steps, dict) else {} + def _todo_checkpoints(proposal: Mapping[str, object]) -> dict[str, object]: + return todo_checkpoints(proposal) def _apply_todo_create( - self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any], - ) -> dict[str, Any]: - from ..chat_actions import ProtectedActionGate, _opaque - - goal_id = str(parameters["goal_id"]) - source = resolve_chat_todo_source(self, goal_id) - agent_id = parameters.get("agent_id") - start_execution = parameters.get("start_execution") is True - steps = self._todo_checkpoints(proposal) - assignment_completed = isinstance(steps.get("todo_assigned"), dict) - todo_step = steps.get("todo_created") - if isinstance(todo_step, dict) and todo_step.get("todo_id"): - todo_id = _opaque(todo_step.get("todo_id"), field="todo_id") - canonical_receipt = todo_step.get("canonical_receipt") - if not isinstance(canonical_receipt, dict): - raise ValueError("Todo creation checkpoint is malformed") - binding = todo_step.get("source") - current_fingerprint = str( - proposal.get("expected_state_fingerprint") or "" - ) - if "source" not in todo_step: - try: - assignment = steps.get("todo_assigned") - if isinstance(assignment, dict) and (not agent_id or assignment.get("todo_id") != todo_id - or assignment.get("agent_id") != str(agent_id)): - raise ChatTodoSourceChanged("The saved assignment does not identify this Task and Agent.") - authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) - if start_execution and agent_id and authority: - # A committed claim can predate the corresponding Chat checkpoint. - claim_completed = source.has_managed_task_claim( - proposal_id, todo_id, str(agent_id), authority["source_authority"], - ) - if assignment_completed and not claim_completed: - # Older releases submitted the Turn after a plain assignment. - _, turn = self._read_confirmed_task(proposal_id, parameters, todo_id, steps) - if turn is None or not self._task_turn_dispatched(turn): - raise ChatTodoSourceChanged("The saved Task start claim is unavailable.") - assignment_completed = assignment_completed or claim_completed - binding = source.recover_legacy_creation( - todo_id=todo_id, preview_id=current_fingerprint, receipt=canonical_receipt, authority=authority, - assignment_pending=bool(agent_id) and not assignment_completed, - ) - if not assignment_completed and agent_id and agent_id not in registered_agent_ids_for_goal(source.goal): - raise ChatTodoSourceChanged("The selected Agent is no longer registered for the Goal") - except (ChatTodoSourceChanged, LocalCoordinationAuthorityUnavailable) as error: - summary = f"The original confirmation recorded Todo {todo_id}. Its assignment source could not be verified." - next_action = "Restore the original Goal source and retry, or review the assignment from the existing Todo." - current = error.verified_todo if isinstance(error, ChatTodoSourceChanged) else None - if current is not None: - assignee = current.get("claimed_by") - assignment_state = f"Its current assignee is {assignee}." if assignee else "It is currently unassigned." - summary = ( - f"The original confirmation created Todo {todo_id}. {assignment_state} " - "The original assignment could not be verified." - ) - next_action = "Open the existing Todo to review its current assignment." - raise ProtectedActionGate("todo.create", gate={ - "kind": "canonical_authority_required", - "summary": summary, - "next_action": next_action, - }) from error - self.store.save_checkpoint(proposal_id, step="todo_created", receipt={**todo_step, "source": binding}) - if not isinstance(binding, dict): - raise ValueError("Todo creation checkpoint source is malformed") - source.require_review(binding) - else: - if agent_id and agent_id not in registered_agent_ids_for_goal(source.goal): - raise ValueError("the selected Agent is no longer registered for this Goal") - authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) - if not isinstance(authority.get("store_identity"), str): - raise ValueError("The Goal's Todo authority identity is unavailable") - current = build_todo_review_preview( - **source.writer_scope(), - goal_id=goal_id, - text=str(parameters["text"]), - priority=parameters.get("priority"), - source_identity=source.source_identity, - ) - current_fingerprint = str(current["preview_id"]) - if current_fingerprint != proposal.get("expected_state_fingerprint"): - stale = self.store.apply( - proposal_id, - current_state_fingerprint=current_fingerprint, - receipt={}, - ) - return {"proposal": stale, "turn": None} - applied = apply_todo_review_preview( - **source.writer_scope(), - goal_id=goal_id, - text=str(parameters["text"]), - priority=parameters.get("priority"), - preview_id=current_fingerprint, - expected_registry_sha256=source.registry_sha256, - routing_registry_witness=source.routing_registry_witness, - source_identity=source.source_identity, - return_authority_write=True, - ) - canonical_receipt = applied["receipt"] - todo_id = _opaque(canonical_receipt["todo_id"], field="todo_id") - binding = { - **applied["authority_write"], - "source_identity": source.source_identity, - "store_identity": authority["store_identity"], - "registry_sha256": source.registry_sha256, - } - self.store.save_checkpoint( - proposal_id, - step="todo_created", - receipt={ - "todo_id": todo_id, - "canonical_receipt": canonical_receipt, - "source": binding, - }, - ) - if agent_id and not start_execution and not assignment_completed: - def apply_assignment(current_source: ChatTodoSource, revision: str) -> dict[str, Any]: - return update_goal_todo( - **current_source.writer_scope(), - goal_id=goal_id, - todo_id=todo_id, - claimed_by=str(agent_id), - agent_id=str(agent_id), - authority_reason="owner-confirmed typed Chat action", - update_operation_id=f"chat-assign:{proposal_id}", - update_expected_provider_revision=revision, - update_expected_registry_sha256=current_source.registry_sha256, - routing_registry_witness=current_source.routing_registry_witness, - dry_run=False, - ) + self: ChatTodoActionHost, + proposal_id: str, + proposal: Mapping[str, object], + parameters: Mapping[str, object], + ) -> dict[str, object]: + return apply_todo_create(self, proposal_id, proposal, parameters) - self._apply_created_todo_assignment( - proposal_id, goal_id=goal_id, todo_id=todo_id, binding=binding, steps=steps, apply=apply_assignment, - ) - self.store.save_checkpoint( - proposal_id, - step="todo_assigned", - receipt={"todo_id": todo_id, "agent_id": str(agent_id)}, - ) - receipt = { - "receipt_id": str(canonical_receipt["receipt_id"]), - "outcome": str(canonical_receipt["outcome"]), - "projection_verified": True, - "resource_ids": { - "goal_id": str(canonical_receipt["goal_id"]), - "todo_id": todo_id, - **({"agent_id": str(agent_id)} if agent_id else {}), - }, - "canonical_receipt": canonical_receipt, - } - turn_result = None - if start_execution: - source = resolve_chat_todo_source(self, goal_id) - source.require_review(binding) - turn_result = self._start_confirmed_task( - proposal_id, parameters, todo_id, steps, source=source, binding=binding, - ) - receipt["resource_ids"].update( - {"session_id": turn_result["session_id"], "turn_id": turn_result["turn_id"]} - ) - receipt["outcome"] = "task_execution_started" - stored = self.store.apply( + def _apply_created_todo_assignment( + self: ChatTodoActionHost, + proposal_id: str, + *, + goal_id: str, + todo_id: str, + binding: Mapping[str, object], + steps: Mapping[str, object], + apply: Callable[[ChatTodoSource, str], dict[str, object]], + ) -> dict[str, object]: + return apply_created_todo_assignment( + self, proposal_id, - current_state_fingerprint=current_fingerprint, - receipt=receipt, + goal_id=goal_id, + todo_id=todo_id, + binding=binding, + steps=steps, + apply_mutation=apply, ) - return {"proposal": stored, "turn": turn_result} - - def _apply_created_todo_assignment( - self, proposal_id: str, *, goal_id: str, todo_id: str, binding: dict[str, Any], - steps: dict[str, Any], apply: Callable[[ChatTodoSource, str], dict[str, Any]], - ) -> dict[str, Any]: - def observe() -> tuple[ChatTodoSource, dict[str, Any]]: - source = resolve_chat_todo_source(self, goal_id) - source.require_review(binding) - authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) - source.require_created_todo(binding, authority) - return source, authority - - source, _ = observe() - basis = steps.get("todo_assignment_basis", binding) - try: - return apply(source, basis["provider_revision"]) - except LocalCoordinationAuthorityUnavailable as error: - if error.code != "provider_revision_mismatch": - raise - - # Only a definitive stale-revision rejection permits a new CAS basis. - # Preserve it before dispatch so a lost response replays the same intent. - source, authority = observe() - revision = source.current_assignment_revision(binding, authority, todo_id) - self.store.save_checkpoint(proposal_id, step="todo_assignment_basis", receipt={"provider_revision": revision}) - return apply(source, revision) @contextmanager def _confirmed_task_commit( - self, *, goal_id: str, todo_id: str, endpoint: str, project: Path, - claim: dict[str, Any], source: ChatTodoSource, binding: dict[str, Any], + self: ChatTodoActionHost, + *, + goal_id: str, + todo_id: str, + endpoint: str, + project: Path, + claim: Mapping[str, object], + source: ChatTodoSource, + binding: Mapping[str, object], ) -> Iterator[None]: """Fence acceptance with the same registry and canonical writers as Stop and Todo edits.""" - invoked = self.registry_path.resolve() - runtime = source.runtime_root - targets = (shadow_maintenance_lock_target(runtime, goal_id), source.registry_path) - if source.registry_path != invoked: - targets += (invoked,) - with ExitStack() as locks: - for target in targets: - locks.enter_context(exclusive_cross_runtime_file_lock(target, operation="confirm_task_admission")) - current_source = resolve_chat_todo_source(self, goal_id) - current_source.require_review(binding) - goal = current_source.goal - if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal): - raise ValueError("The Task's Goal is no longer active") - if Path(str(goal.get("repo") or ".")).expanduser().resolve() != project: - raise ValueError("The reviewed Task's project root changed") - owner = claim["claimed_by"] - if self._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner: - raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent") - authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id, include_leases=True) - current_source.require_created_todo(binding, authority) - todo = next((row for row in authority["todos"] if row["todo_id"] == todo_id), None) - if (todo is None or todo.get("role") != "agent" or todo.get("status") != "open" - or todo.get("claimed_by") != owner or authority["handoff_mode"] != claim["handoff_mode"]): - raise ValueError("The reviewed Task assignment changed before launch") - if authority["handoff_mode"] == "hard_lease": - lease = next((row for row in authority["leases"] if row["todo_id"] == todo_id), None) - original = claim.get("lease") - if (not lease or not isinstance(original, dict) or not lease_is_active(lease) - or any(lease.get(key) != original.get(key) for key in ("owner", "idempotency_key", "lease_epoch"))): - raise ValueError("The reviewed Task execution lease changed before launch") + with confirmed_task_commit( + self, + goal_id=goal_id, + todo_id=todo_id, + endpoint=endpoint, + project=project, + claim=claim, + source=source, + binding=binding, + ): yield @staticmethod def _read_task_start( - chat: ChatSessionStore, *, goal_id: str, agent_id: str, channel_id: str, - client_turn_id: str, checkpoint: dict[str, Any] | None, - ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: - from ..chat_actions import _opaque - - if checkpoint is not None: - sid = _opaque(checkpoint.get("session_id"), field="session_id") - session = chat.load_session(sid) - if (session is None or session.get("goal_id") != goal_id - or session.get("agent_id") != agent_id or session.get("channel_id") != channel_id): - raise ValueError("The original Task Session is unavailable") - return session, chat.turn_for_client(sid, client_turn_id) - - # A process may have persisted the Session before the proposal's - # checkpoint. Include closed Sessions so retry cannot replace one. - sessions = chat.session_candidates(goal_id=goal_id, agent_id=agent_id, channel_id=channel_id) - matches = [ - (session, turn) for session in sessions - if (turn := chat.turn_for_client(session["session_id"], client_turn_id)) is not None - ] - if len(matches) == 1: - return matches[0] - if len(sessions) > 1: - raise ValueError("The original Task Session is ambiguous") - return (sessions[0] if sessions else None), None + chat: TodoSessionStoreProtocol, + *, + goal_id: str, + agent_id: str, + channel_id: str, + client_turn_id: str, + checkpoint: Mapping[str, object] | None, + ) -> tuple[dict[str, object] | None, dict[str, object] | None]: + return read_task_start( + chat, + goal_id=goal_id, + agent_id=agent_id, + channel_id=channel_id, + client_turn_id=client_turn_id, + checkpoint=checkpoint, + ) - def _pending_applied_task_receipt(self, proposal: dict[str, Any]) -> dict[str, Any] | None: + def _pending_applied_task_receipt( + self: ChatTodoActionHost, + proposal: Mapping[str, object], + ) -> dict[str, object] | None: """Find the exact accepted Turn whose worker has yet to start.""" - parameters = proposal.get("normalized_parameters") or {} - receipt = proposal.get("receipt") or {} - if (proposal.get("status") != "applied" or proposal.get("action_kind") != "todo.create" - or parameters.get("start_execution") is not True - or proposal.get("permission_classification") != "durable_write" - or (proposal.get("context") or {}).get("binding_id") - or receipt.get("outcome") != "task_execution_started" - or receipt.get("projection_verified") is not True): - return None - resources = receipt.get("resource_ids") - canonical = receipt.get("canonical_receipt") - if not isinstance(resources, dict) or not isinstance(canonical, dict): - return None - goal_id = parameters.get("goal_id") - todo_id, sid, tid = (resources.get(key) for key in ("todo_id", "session_id", "turn_id")) - if (not all(isinstance(value, str) and value for value in (goal_id, todo_id, sid, tid)) - or resources.get("goal_id") != goal_id or canonical.get("goal_id") != goal_id - or canonical.get("todo_id") != todo_id or canonical.get("status") != "applied" - or canonical.get("preview_id") != proposal.get("expected_state_fingerprint")): - return None - chat = getattr(self.runtime_controller, "store", None) or self.chat_store - if chat is None: - return None - try: - turn = chat.load_turn(sid, tid) - except (OSError, ValueError): - return None - if (turn and turn.get("session_id") == sid and turn.get("turn_id") == tid - and turn.get("client_turn_id") == f"task-start-{proposal['proposal_id']}" - and turn.get("status") == "queued" and not (turn.get("started_at") or turn.get("upstream_turn_id"))): - return resources - return None - - def project_task_dispatch(self, proposal: dict[str, Any]) -> dict[str, Any]: - if self._pending_applied_task_receipt(proposal) is not None: - return {**proposal, "task_execution_dispatch_pending": True} - return proposal + return pending_applied_task_receipt(self, proposal) - def _recover_applied_task(self, proposal: dict[str, Any]) -> dict[str, Any] | None: - execution = self._pending_applied_task_receipt(proposal) - if execution is None: - return self._turn_from_receipt(proposal.get("receipt")) + def project_task_dispatch( + self: ChatTodoActionHost, + proposal: Mapping[str, object], + ) -> dict[str, object]: + return project_task_dispatch_record(self, proposal) - parameters = proposal["normalized_parameters"] - goal_id, todo_id = parameters["goal_id"], execution["todo_id"] - source = resolve_chat_todo_source(self, goal_id) - steps = self._todo_checkpoints(proposal) - created = steps.get("todo_created", {}) - canonical = proposal["receipt"]["canonical_receipt"] - if not isinstance(created, dict) or (created and ( - created.get("todo_id") != todo_id or created.get("canonical_receipt") != canonical - )): - raise ValueError("The accepted Task's creation checkpoint changed") - authority = read_canonical_todos_if_promoted(runtime_root=source.runtime_root, goal_id=goal_id) - if "source" in created: - binding = created["source"] - if not isinstance(binding, dict): - raise ValueError("Todo creation checkpoint source is malformed") - else: - binding = source.recover_legacy_creation( - todo_id=todo_id, preview_id=proposal["expected_state_fingerprint"], receipt=canonical, - authority=authority, assignment_pending=False, - ) - source.require_created_todo(binding, authority) - if not source.has_managed_task_claim(proposal["proposal_id"], todo_id, parameters["agent_id"], - authority["source_authority"]): - raise ChatTodoSourceChanged("The saved Task start claim is unavailable.") - return self._start_confirmed_task( - proposal["proposal_id"], parameters, todo_id, steps, source=source, binding=binding, - applied_execution=execution, - ) + def _recover_applied_task( + self: ChatTodoActionHost, + proposal: Mapping[str, object], + ) -> dict[str, object] | None: + return recover_applied_task(self, proposal) def _read_confirmed_task( - self, proposal_id: str, parameters: dict[str, Any], todo_id: str, steps: dict[str, Any], - *, execution: dict[str, Any] | None = None, - ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]: - controller = self.runtime_controller - chat = getattr(controller, "store", None) or self.chat_store - if chat is None: - raise ValueError("Chat Runtime Controller is unavailable") - if execution is None: - execution = steps.get("execution_started") - session, turn = self._read_task_start( - chat, goal_id=str(parameters["goal_id"]), - agent_id=str(parameters.get("endpoint_id") or parameters["agent_id"]), channel_id=f"task.{todo_id}", - client_turn_id=f"task-start-{proposal_id}", - checkpoint=execution if execution is not None else steps.get("task_session_opened"), - ) - if execution is not None and (turn is None or turn["turn_id"] != execution.get("turn_id")): - raise ValueError("The original Task Turn is unavailable") - if turn is not None and turn.get("message") != str(parameters["text"]): - raise ValueError("The original Task Turn request changed") - return session, turn + self: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + todo_id: str, + steps: Mapping[str, object], + *, + execution: Mapping[str, object] | None = None, + ) -> tuple[dict[str, object] | None, dict[str, object] | None]: + return read_confirmed_task(self, proposal_id, parameters, todo_id, steps, execution=execution) @staticmethod - def _task_turn_dispatched(turn: dict[str, Any]) -> bool: - return turn.get("status") in TERMINAL_TURN_STATES or bool(turn.get("started_at") or turn.get("upstream_turn_id")) + def _task_turn_dispatched(turn: Mapping[str, object]) -> bool: + return task_turn_dispatched(turn) def _start_confirmed_task( - self, proposal_id: str, parameters: dict[str, Any], todo_id: str, steps: dict[str, Any], - *, source: ChatTodoSource, binding: dict[str, Any], applied_execution: dict[str, Any] | None = None, - ) -> dict[str, Any]: - from ..chat_actions import _opaque - - controller = self.runtime_controller - goal_id = str(parameters["goal_id"]) - owner = str(parameters["agent_id"]) - endpoint = str(parameters.get("endpoint_id") or owner) - message = str(parameters["text"]) - channel_id = f"task.{todo_id}" - client_turn_id = f"task-start-{proposal_id}" - opened = steps.get("task_session_opened") - execution = applied_execution if applied_execution is not None else steps.get("execution_started") - session, turn = self._read_confirmed_task(proposal_id, parameters, todo_id, steps, execution=execution) - - # An already dispatched or terminal Turn is readback. Only work that - # still needs dispatch passes through the current Goal and claim gates. - created = False - if turn is None or not self._task_turn_dispatched(turn): - if controller is None: - raise ValueError("Chat Runtime Controller is unavailable") - if session is not None and session.get("status") == "closed": - raise ValueError("The original Task Session is closed") - goal = source.goal - if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal): - raise ValueError("The Task's Goal is no longer active") - project = Path(str(goal.get("repo") or ".")).expanduser().resolve() - if not project.is_dir(): - raise ValueError("the Goal project root is unavailable") - self._agent_eligibility(endpoint, project=project) - if parameters.get("endpoint_id") and self._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner: - raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent") - claim_args: dict[str, Any] = { - "goal_id": goal_id, "todo_id": todo_id, - "claimed_by": owner, "agent_id": owner, "claim_only": True, "manage_execution": True, - } - - def apply_claim(current_source: ChatTodoSource, revision: str) -> dict[str, Any]: - return update_goal_todo( - **current_source.writer_scope(), **claim_args, - claim_operation_id=task_start_claim_operation_id(proposal_id), dry_run=False, - claim_expected_provider_revision=revision, - claim_expected_registry_sha256=current_source.registry_sha256, - routing_registry_witness=current_source.routing_registry_witness, - ) - - if applied_execution is None: - claim = self._apply_created_todo_assignment( - proposal_id, goal_id=goal_id, todo_id=todo_id, binding=binding, steps=steps, apply=apply_claim, - ) - else: - # Replay the accepted claim using the same intent. A stale - # basis cannot authorize another claim on an applied card. - claim = apply_claim(source, steps.get("todo_assignment_basis", binding)["provider_revision"]) - if claim["handoff_mode"] == "soft_claim" and claim["status"] in {"recovered", "replayed"}: - # A past soft claim still needs a read-only current-owner check. - if update_goal_todo(**source.writer_scope(), **claim_args, dry_run=True)["changed"]: - raise ValueError("The reviewed Task assignment changed before launch") - if applied_execution is None and not isinstance(steps.get("todo_assigned"), dict): - self.store.save_checkpoint( - proposal_id, step="todo_assigned", receipt={"todo_id": todo_id, "agent_id": owner}, - ) - if session is None: - session, _ = controller.open_session( - goal_id=goal_id, agent_id=endpoint, work_dir=project, objective=message, - mode="resume_latest", channel_id=channel_id, agent_goal_id=goal_id, - ) - sid = _opaque(session.get("session_id"), field="session_id") - if opened is None and execution is None: - self.store.save_checkpoint(proposal_id, step="task_session_opened", receipt={"session_id": sid}) - turn, created = controller.submit_turn( - session_id=sid, client_turn_id=client_turn_id, message=message, work_dir=project, objective=message, - _goal_commit=lambda: self._confirmed_task_commit( - goal_id=goal_id, todo_id=todo_id, endpoint=endpoint, project=project, claim=claim, - source=source, binding=binding, - ), - ) - - identity = { - "session_id": _opaque(turn.get("session_id"), field="session_id"), - "turn_id": _opaque(turn.get("turn_id"), field="turn_id"), - } - if execution is None: - self.store.save_checkpoint(proposal_id, step="execution_started", receipt=identity) - return {**identity, "status": str(turn.get("status") or "accepted"), "created": created} + self: ChatTodoActionHost, + proposal_id: str, + parameters: Mapping[str, object], + todo_id: str, + steps: Mapping[str, object], + *, + source: ChatTodoSource, + binding: Mapping[str, object], + applied_execution: Mapping[str, object] | None = None, + ) -> dict[str, object]: + return start_confirmed_task( + self, + proposal_id, + parameters, + todo_id, + steps, + source=source, + binding=binding, + applied_execution=applied_execution, + ) def _run_todo_update( - self, parameters: dict[str, Any], *, dry_run: bool, - basis: dict[str, Any] | None = None, operation_id: str | None = None, - ) -> dict[str, Any]: - goal_id = str(parameters["goal_id"]) - operation = str(parameters.get("operation") or "edit") - reviewed = parameters.get("review_basis") - if dry_run and reviewed is not None and ( - basis is None or any(basis.get(key) != value for key, value in reviewed.items())): - raise ValueError("The Task source changed. Reload its complete requirements before saving.") - source = resolve_chat_todo_source(self, goal_id) - if basis is not None: - source.require_review(basis) - # Transport only caller-supplied proof. The terminal owner revalidates - # the execution; a lease read or a Todo claim is never substitute proof. - proof = {key: parameters[key] for key in ( - "task_lease_idempotency_key", "task_lease_expected_version", - ) if key in parameters} if operation == "complete" else {} - if operation == "complete" and (basis is None or - basis.get("schema_version") == "loopx_chat_canonical_terminal_basis_v0"): - return complete_goal_todo( - **source.writer_scope(), - routing_registry_witness=source.routing_registry_witness, - goal_id=goal_id, - todo_id=str(parameters["todo_id"]), - note=parameters.get("note"), - no_followup=bool(parameters.get("no_followup", True)), - successor_todo_ids=parameters.get("successor_todo_ids"), - agent_id=parameters.get("agent_id"), - authority_reason="owner-confirmed typed Chat action", - dry_run=dry_run, - **proof, - **self._reviewed_terminal_options(basis, operation_id), - ) - status = parameters.get("status") - if operation == "complete": - status = "done" - elif operation == "block": - status = "blocked" - elif operation == "defer": - status = "deferred" - return update_goal_todo( - **source.writer_scope(), - routing_registry_witness=source.routing_registry_witness, - goal_id=goal_id, - todo_id=str(parameters["todo_id"]), - text=parameters.get("text"), - priority=parameters.get("priority"), - clear_priority=(parameters.get("clear_priority", False) or - ("priority" in parameters and parameters["priority"] is None)), - status=status, - **({"role": "user", "no_followup": bool(parameters.get("no_followup", True))} - if operation == "complete" else {}), - # The established block control uses note as its pause reason; - # preserve the task's existing notes. Explicit ordinary note edits - # and lifecycle effects still share the canonical transaction. - note=(parameters.get("note") if operation != "block" or basis is None else None), - reason=(parameters.get("note") or "Owner requested deferral") if operation in {"block", "defer"} else ( - parameters.get("note") or "Owner explicitly requested task resumption" if status == "open" else None), - claimed_by=( - parameters.get("agent_id") if operation == "reassign" else None - ), - resume_when=parameters.get("resume_when"), - clear_resume_when=(operation == "block" or (status == "open" and not parameters.get("resume_when"))) and basis is not None, - successor_todo_ids=parameters.get("successor_todo_ids"), - agent_id=parameters.get("agent_id"), - authority_reason="owner-confirmed typed Chat action", - dry_run=dry_run, - **proof, - **self._reviewed_update_options(basis, operation_id), - ) + self: ChatTodoActionHost, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: + return run_todo_update(self, parameters, dry_run=dry_run, basis=basis, operation_id=operation_id) def _run_gate_resolve( - self, parameters: dict[str, Any], *, dry_run: bool, - basis: dict[str, Any] | None = None, operation_id: str | None = None, - ) -> dict[str, Any]: - # The typed User completion owner decides whether this source may carry - # the outcome and what it does to the dependent; the App only records it. - goal_id = str(parameters["goal_id"]) - source = resolve_chat_todo_source(self, goal_id) - if basis is not None: - source.require_review(basis) - return complete_goal_todo( - **source.writer_scope(), - routing_registry_witness=source.routing_registry_witness, - goal_id=goal_id, - todo_id=str(parameters["todo_id"]), - role="user", - decision_outcome=str(parameters["decision"]), - evidence=parameters.get("note"), - no_followup=True, - agent_id=parameters.get("agent_id"), - authority_reason="owner-confirmed typed Chat decision", - dry_run=dry_run, - **self._reviewed_terminal_options(basis, operation_id), - ) + self: ChatTodoActionHost, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: + return run_gate_resolve(self, parameters, dry_run=dry_run, basis=basis, operation_id=operation_id) @staticmethod def _reviewed_terminal_options( - basis: dict[str, Any] | None, operation_id: str | None, - ) -> dict[str, Any]: - if basis is None: - return {} - if basis.get("schema_version") != "loopx_chat_canonical_terminal_basis_v0": - raise ValueError("unsupported canonical terminal review basis; regenerate preview") - return {"completion_turn_key": operation_id, "terminal_review_basis": { - "provider_revision": basis["provider_revision"], "registry_sha256": basis["registry_sha256"], - }} + basis: Mapping[str, object] | None, + operation_id: str | None, + ) -> dict[str, object]: + return reviewed_terminal_options(basis, operation_id) @staticmethod def _reviewed_update_options( - basis: dict[str, Any] | None, operation_id: str | None, - ) -> dict[str, Any]: - if basis is None: - return {} - if basis.get("schema_version") != "loopx_chat_canonical_update_basis_v0": - raise ValueError("unsupported canonical update review basis; regenerate preview") - return { - "update_operation_id": operation_id, - "update_expected_provider_revision": basis["provider_revision"], - "update_expected_registry_sha256": basis["registry_sha256"], - } + basis: Mapping[str, object] | None, + operation_id: str | None, + ) -> dict[str, object]: + return reviewed_update_options(basis, operation_id) def _canonical_update_basis( - self, goal_id: str, *, completion_todo_id: str | None = None, + self: ChatTodoActionHost, + goal_id: str, + *, + completion_todo_id: str | None = None, decision: bool = False, - ) -> dict[str, Any] | None: - source = resolve_chat_todo_source(self, goal_id) - authority = read_canonical_todos_if_promoted( - runtime_root=source.runtime_root, - goal_id=goal_id, + ) -> dict[str, object] | None: + return canonical_update_basis( + self, + goal_id, + completion_todo_id=completion_todo_id, + decision=decision, ) - current = resolve_chat_todo_source(self, goal_id) - if (current.source_identity, current.registry_sha256) != ( - source.source_identity, source.registry_sha256): - raise ValueError("Todo authority registration changed while reading; retry") - if authority is None: - return None - # User updates retain their combined edit/completion contract. Agent - # completion, Monitor stop and a User decision outcome bind the - # dedicated terminal transaction, the only owner of decision_outcome. - terminal = decision or completion_todo_id is not None and not any( - todo.get("todo_id") == completion_todo_id and todo.get("role") == "user" - for todo in authority["todos"]) - return { - "schema_version": ("loopx_chat_canonical_terminal_basis_v0" if terminal else - "loopx_chat_canonical_update_basis_v0"), - "provider_revision": authority["provider_revision"], - "source_authority": authority["source_authority"], - "registry_sha256": source.registry_sha256, - "source_identity": source.source_identity, - } def _apply_reviewed_todo_edit( - self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any], - ) -> dict[str, Any]: - """Recover the canonical operation before testing present-day freshness. - - CAS admits a new edit; the immutable receipt proves a previous edit. - Both paths drain the current projection, never an old receipt's state. - """ - from ..chat_actions import _digest, _opaque - from ..chat_action_store import ActionConflictError - - operation_id = f"chat-update:{proposal_id}" - basis = proposal["canonical_update_basis"] - action_kind = proposal["action_kind"] - run = {"monitor.update": self._run_monitor_update, - "gate.resolve": self._run_gate_resolve}.get(action_kind, self._run_todo_update) - terminal = action_kind == "gate.resolve" or parameters.get("operation") in {"complete", "stop"} - try: - result = run(parameters, dry_run=False, basis=basis, operation_id=operation_id) - except ChatTodoSourceChanged as error: - failed = self.store.mark_failed( - proposal_id, error_code="canonical_update_source_changed", message=str(error), - details={"operation_id": operation_id}, - ) - return {"proposal": failed, "turn": None} - except LocalCoordinationAuthorityUnavailable as error: - if error.code == COMPLETION_VALIDATION_IN_PROGRESS: - # The original caller still owns its result and proposal. - raise ActionConflictError(str(error)) from error - if (terminal and error.code == "authority_source_changed" - and error.payload.get("completion_validation_executed") is True): - self.store.mark_failed( - proposal_id, error_code="canonical_update_validation_source_changed", - message="Todo authority registration changed during completion validation; retry", - details={"operation_id": operation_id, "reason_code": error.code}, - ) - raise ValueError( - "Todo authority registration changed during completion validation; retry" - ) from error - if error.code in {"provider_revision_mismatch", "authority_source_changed", "provider_revision_conflict"}: - # The native transaction first established that no matching - # historical receipt exists. This is a rejected new edit. - stale = self.store.apply(proposal_id, current_state_fingerprint=_digest({ - "expected": proposal["expected_state_fingerprint"], - "conflict": error.code, - }), receipt={}) - return {"proposal": stale, "turn": None} - failed = self.store.mark_failed( - proposal_id, error_code="canonical_update_retry_required", - message="The edit is not yet verified. Retry this proposal to recover the original operation.", - details={"operation_id": operation_id, "reason_code": error.code}, - ) - return {"proposal": failed, "turn": None} - if result.get("ok") is not True: - failed = self.store.mark_failed(proposal_id, error_code="canonical_update_validation_failed", - message="Completion validation did not pass. The Todo was not completed; retry after resolving the validation failure.", - details={"operation_id": operation_id, "reason_code": result.get("reason_code")}) - return {"proposal": failed, "turn": None} - original = result.get("original_receipt") or result - todo_id = _opaque(result.get("todo_id"), field="todo_id") - self.store.save_checkpoint(proposal_id, step="canonical_update", receipt={ - "operation_id": operation_id, "todo_id": todo_id, - "changed": original.get("changed") is True, - }) - if not projection_delivery_requires_ack(result["projection_delivery"]): - failed = self.store.mark_failed( - proposal_id, error_code="canonical_update_projection_pending", - message="The edit was committed. Display delivery is pending; retry this proposal to restore the current view.", - details={"operation_id": operation_id, "canonical_committed": True}, - ) - return {"proposal": failed, "turn": None} - operation = parameters.get("operation", "edit") - outcome = ("gate_resolved" if action_kind == "gate.resolve" else - {"pause": "monitor_paused", "resume": "monitor_resumed", "edit": "monitor_updated", "stop": "monitor_stopped"}[operation] - if action_kind == "monitor.update" else - "todo_completed" if operation == "complete" else - "todo_updated" if original.get("changed") else "todo_unchanged") - stored = self.store.apply(proposal_id, - current_state_fingerprint=str(proposal["expected_state_fingerprint"]), receipt={ - "receipt_id": _digest({"proposal_id": proposal_id, "todo_id": todo_id})[:32], - "outcome": outcome, "projection_verified": True, - "projection_delivery": result["projection_delivery"], - "operation_id": operation_id, - "canonical_status": result.get("provider_status", result["status"]), - "resource_ids": {"goal_id": str(parameters["goal_id"]), "todo_id": todo_id}, - **(_decision_readback(result) if action_kind == "gate.resolve" else {}), - }) - return {"proposal": stored, "turn": None} + self: TodoActionServiceSelf, + proposal_id: str, + proposal: Mapping[str, object], + parameters: dict[str, object], + ) -> dict[str, object]: + """Recover the canonical operation before testing present-day freshness.""" + return apply_reviewed_todo_edit(self, proposal_id, proposal, parameters) def _apply_todo_update( - self, proposal_id: str, proposal: dict[str, Any], parameters: dict[str, Any] - ) -> dict[str, Any]: - from ..chat_actions import _digest, _opaque - - if proposal.get("canonical_update_basis") is not None: - return self._apply_reviewed_todo_edit(proposal_id, proposal, parameters) - goal_id = str(parameters["goal_id"]) - current_fingerprint = self._goal_state_fingerprint(goal_id) - if current_fingerprint != proposal.get("expected_state_fingerprint"): - stale = self.store.apply( - proposal_id, current_state_fingerprint=current_fingerprint, receipt={} - ) - return {"proposal": stale, "turn": None} - operation = str(parameters.get("operation") or "edit") - decision = proposal.get("action_kind") == "gate.resolve" - result = (self._run_gate_resolve if decision else self._run_todo_update)(parameters, dry_run=False) - todo_id = _opaque(result.get("todo_id"), field="todo_id") - receipt = { - "receipt_id": _digest({"proposal_id": proposal_id, "todo_id": todo_id})[ - :32 - ], - "outcome": ( - "gate_resolved" - if decision - else "todo_completed" - if operation == "complete" - else "todo_updated" if result.get("changed") else "todo_unchanged" - ), - "projection_verified": True, - "resource_ids": {"goal_id": goal_id, "todo_id": todo_id}, - **(_decision_readback(result) if decision else {}), - } - stored = self.store.apply( - proposal_id, current_state_fingerprint=current_fingerprint, receipt=receipt - ) - return {"proposal": stored, "turn": None} + self: TodoActionServiceSelf, + proposal_id: str, + proposal: Mapping[str, object], + parameters: dict[str, object], + ) -> dict[str, object]: + return apply_todo_update(self, proposal_id, proposal, parameters) diff --git a/tests/control_plane/test_chat_todo_actions_contract.py b/tests/control_plane/test_chat_todo_actions_contract.py new file mode 100644 index 0000000000..b757131552 --- /dev/null +++ b/tests/control_plane/test_chat_todo_actions_contract.py @@ -0,0 +1,637 @@ +"""Contract, negative-path, and parity tests for Zero-Any Chat Todo action modules.""" + +from __future__ import annotations + +import ast +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +import importlib.util +import io +from pathlib import Path +import tokenize +from types import MappingProxyType + +import pytest + +from loopx.chat import todo_action_contracts, todo_action_create, todo_action_tasks, todo_action_updates, todo_actions +from loopx.chat.action_store_common import ActionConflictError, _canonical_digest +from loopx.chat.todo_action_contracts import ( + TodoRuntimeControllerProtocol, + TodoTurnLoaderProtocol, +) +from loopx.chat.todo_actions import ChatTodoActionMixin, _decision_readback +from loopx.chat.todo_source import ChatTodoSource, ChatTodoSourceChanged +from loopx.control_plane.coordination.local_authority import LocalCoordinationAuthorityUnavailable +from loopx.control_plane.todos.completion_validation import COMPLETION_VALIDATION_IN_PROGRESS + +_MODULE_PATHS = ( + "loopx/chat/todo_actions.py", + "loopx/chat/todo_action_contracts.py", + "loopx/chat/todo_action_tasks.py", + "loopx/chat/todo_action_create.py", + "loopx/chat/todo_action_updates.py", +) + + +def _as_map(value: object) -> Mapping[str, object]: + assert isinstance(value, Mapping) + return value + + +@dataclass +class _StubActionStore: + applied: list[tuple[str, str, dict[str, object]]] = field(default_factory=list) + checkpoints: list[tuple[str, str, dict[str, object]]] = field(default_factory=list) + failed: list[tuple[str, str, str, dict[str, object]]] = field(default_factory=list) + + def apply( + self, + proposal_id: str, + *, + current_state_fingerprint: str, + receipt: Mapping[str, object], + ) -> dict[str, object]: + payload = dict(receipt) + self.applied.append((proposal_id, current_state_fingerprint, payload)) + return { + "proposal_id": proposal_id, + "status": "applied" if payload else "stale", + "expected_state_fingerprint": current_state_fingerprint, + "receipt": payload, + } + + def save_checkpoint( + self, + proposal_id: str, + *, + step: str, + receipt: Mapping[str, object], + ) -> dict[str, object]: + payload = dict(receipt) + self.checkpoints.append((proposal_id, step, payload)) + return {"proposal_id": proposal_id, "step": step, "receipt": payload} + + def mark_failed( + self, + proposal_id: str, + *, + error_code: str, + message: str, + details: Mapping[str, object] | None = None, + ) -> dict[str, object]: + detail_dict = dict(details or {}) + self.failed.append((proposal_id, error_code, message, detail_dict)) + return { + "proposal_id": proposal_id, + "status": "failed", + "failure": {"error_code": error_code, "message": message, "details": detail_dict}, + } + + +class _StubRuntimeController: + def __init__(self, store: TodoTurnLoaderProtocol | None = None) -> None: + self.store = store + + def capabilities(self) -> Sequence[Mapping[str, object]]: + return () + + def open_session( + self, + *, + goal_id: str, + goal_instance_id: str | None = None, + agent_id: str, + work_dir: Path, + objective: str, + mode: str, + session_id: str | None = None, + channel_id: str, + agent_goal_id: str, + managed_agent_id: str = "", + ) -> tuple[dict[str, object], bool]: + return {"session_id": session_id or "sess-stub"}, True + + def submit_turn( + self, + *, + session_id: str, + client_turn_id: str, + message: str, + work_dir: Path, + objective: str, + display_message: str = "", + ) -> tuple[dict[str, object], bool]: + return {"session_id": session_id, "turn_id": "turn-stub"}, True + + def resume_session_queue(self, *, session_id: str, work_dir: Path, objective: str) -> object: + return None + + +class _StubTodoHost(ChatTodoActionMixin): + def __init__( + self, + *, + registry_path: Path, + store: _StubActionStore | None = None, + chat_store: TodoTurnLoaderProtocol | None = None, + runtime_controller: TodoRuntimeControllerProtocol | None = None, + monitor_runner: Callable[..., Mapping[str, object]] | None = None, + ) -> None: + self.store = store or _StubActionStore() + self.registry_path = registry_path + self.chat_store = chat_store + self.runtime_controller = runtime_controller + self.runtime_root_override: str | None = None + self.monitor_runner = monitor_runner + self.fingerprint = "fp-1" + + def _goal_state_fingerprint(self, goal_id: str) -> str: + return self.fingerprint + + def _agent_eligibility( + self, + agent_id: str, + *, + project: Path | None = None, + requires_tools: bool = True, + require_healthy: bool = True, + ) -> dict[str, object]: + return {"agent_id": agent_id, "available": True} + + def _resolve_goal_agent( + self, + goal_id: str, + endpoint_id: str, + *, + goal: dict[str, object] | None = None, + ) -> str: + return endpoint_id + + def _turn_from_receipt(self, receipt: object) -> dict[str, object] | None: + return {"turn_id": "turn-from-receipt"} if isinstance(receipt, Mapping) else None + + def _run_monitor_update( + self, + parameters: dict[str, object], + *, + dry_run: bool, + basis: dict[str, object] | None = None, + operation_id: str | None = None, + ) -> dict[str, object]: + if self.monitor_runner is not None: + return dict(self.monitor_runner(parameters, dry_run=dry_run, basis=basis, operation_id=operation_id)) + raise AssertionError("monitor runner was not configured") + + +def test_chat_todo_actions_modularization_and_layout_pin() -> None: + root = Path(__file__).resolve().parents[2] + all_paths = (*_MODULE_PATHS, "tests/control_plane/test_chat_todo_actions_contract.py") + for rel_path in all_paths: + text = (root / rel_path).read_text(encoding="utf-8") + lines = text.splitlines() + cap = 550 if rel_path == "loopx/chat/todo_actions.py" else 650 + assert len(lines) <= cap, f"{rel_path} exceeded LOC budget ({len(lines)} > {cap})" + comments = [ + tok.string + for tok in tokenize.generate_tokens(io.StringIO(text).readline) + if tok.type == tokenize.COMMENT + ] + assert not any("type: ignore" in comment for comment in comments), f"{rel_path} must stay free of type: ignore" + assert not any("noqa" in comment for comment in comments), f"{rel_path} must stay free of noqa" + tree = ast.parse(text) + any_nodes = [node for node in ast.walk(tree) if isinstance(node, ast.Name) and node.id == "Any"] + assert any_nodes == [], f"{rel_path} must stay Zero-Any" + if rel_path.startswith("loopx/chat/"): + for node in ast.walk(tree): + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + span = (node.end_lineno or node.lineno) - node.lineno + 1 + assert span <= 85, f"{rel_path}:{node.name} span too large ({span})" + + assert ChatTodoActionMixin.__module__ == "loopx.chat.todo_actions" + assert importlib.util.find_spec("loopx.chat_todo_actions") is None + assert callable(_decision_readback) + for attr in ( + "_todo_checkpoints", + "_apply_todo_create", + "_apply_created_todo_assignment", + "_confirmed_task_commit", + "_read_task_start", + "_pending_applied_task_receipt", + "project_task_dispatch", + "_recover_applied_task", + "_read_confirmed_task", + "_task_turn_dispatched", + "_start_confirmed_task", + "_run_todo_update", + "_run_gate_resolve", + "_reviewed_terminal_options", + "_reviewed_update_options", + "_canonical_update_basis", + "_apply_reviewed_todo_edit", + "_apply_todo_update", + ): + assert hasattr(ChatTodoActionMixin, attr), f"Missing ChatTodoActionMixin.{attr}" + + +def test_option_parsers_readback_and_coercions() -> None: + assert _decision_readback({"decision_outcome": "approved", "unblock_resume": {"state": "resumed"}}) == { + "decision_outcome": "approved", + "unblock_resume_state": "resumed", + } + assert _decision_readback(MappingProxyType({"decision_outcome": "rejected", "unblock_resume": "invalid"})) == { + "decision_outcome": "rejected", + "unblock_resume_state": None, + } + assert ChatTodoActionMixin._reviewed_terminal_options(None, "op-1") == {} + assert ChatTodoActionMixin._reviewed_update_options(None, "op-1") == {} + + terminal_basis = { + "schema_version": todo_action_contracts.CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION, + "provider_revision": "rev-9", + "registry_sha256": "abc123", + } + assert ChatTodoActionMixin._reviewed_terminal_options(terminal_basis, "op-t") == { + "completion_turn_key": "op-t", + "terminal_review_basis": {"provider_revision": "rev-9", "registry_sha256": "abc123"}, + } + update_basis = { + "schema_version": todo_action_contracts.CANONICAL_UPDATE_BASIS_SCHEMA_VERSION, + "provider_revision": "rev-8", + "registry_sha256": "def456", + } + assert ChatTodoActionMixin._reviewed_update_options(update_basis, "op-u") == { + "update_operation_id": "op-u", + "update_expected_provider_revision": "rev-8", + "update_expected_registry_sha256": "def456", + } + with pytest.raises(ValueError, match="unsupported canonical terminal review basis"): + ChatTodoActionMixin._reviewed_terminal_options(update_basis, "op-1") + with pytest.raises(ValueError, match="unsupported canonical update review basis"): + ChatTodoActionMixin._reviewed_update_options(terminal_basis, "op-1") + + assert todo_action_contracts.as_optional_int(None, field="v") is None + assert todo_action_contracts.as_optional_int(7, field="v") == 7 + with pytest.raises(ValueError, match="v must be an integer"): + todo_action_contracts.as_optional_int(True, field="v") + with pytest.raises(ValueError, match="v must be an integer"): + todo_action_contracts.as_optional_int("7", field="v") + + assert todo_action_contracts.as_optional_str_list(None, field="ids") is None + assert todo_action_contracts.as_optional_str_list(("t1", 2), field="ids") == ["t1", "2"] + with pytest.raises(ValueError, match="ids must be a sequence"): + todo_action_contracts.as_optional_str_list("t1", field="ids") + + assert ChatTodoActionMixin._task_turn_dispatched({"status": "queued"}) is False + assert ChatTodoActionMixin._task_turn_dispatched({"status": "queued", "started_at": "2026-01-01T00:00:00Z"}) is True + assert ChatTodoActionMixin._task_turn_dispatched({"status": "completed"}) is True + assert todo_action_contracts.require_str("ok", error="bad") == "ok" + with pytest.raises(ValueError, match="bad"): + todo_action_contracts.require_str("", error="bad") + + +def test_pending_applied_task_dispatch_boundaries(tmp_path: Path) -> None: + turn_record: dict[str, object] = { + "session_id": "sess-1", + "turn_id": "turn-1", + "client_turn_id": "task-start-prop-1", + "status": "queued", + } + + class _TurnStore: + def __init__(self, *, raise_error: Exception | None = None) -> None: + self.raise_error = raise_error + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: + if self.raise_error is not None: + raise self.raise_error + return turn_record + + base_proposal: dict[str, object] = { + "proposal_id": "prop-1", + "status": "applied", + "action_kind": "todo.create", + "permission_classification": "durable_write", + "expected_state_fingerprint": "prev-1", + "context": {"kind": "goal"}, + "normalized_parameters": {"goal_id": "goal-a", "start_execution": True}, + "receipt": { + "outcome": "task_execution_started", + "projection_verified": True, + "resource_ids": { + "goal_id": "goal-a", + "todo_id": "todo-1", + "session_id": "sess-1", + "turn_id": "turn-1", + }, + "canonical_receipt": { + "goal_id": "goal-a", + "todo_id": "todo-1", + "status": "applied", + "preview_id": "prev-1", + }, + }, + } + + host = _StubTodoHost(registry_path=tmp_path / "registry.json", chat_store=_TurnStore()) + projected = host.project_task_dispatch(MappingProxyType(base_proposal)) + assert projected["task_execution_dispatch_pending"] is True + + # Controller store overrides fallback chat_store when present. + ctrl_host = _StubTodoHost( + registry_path=tmp_path / "registry.json", + chat_store=None, + runtime_controller=_StubRuntimeController(store=_TurnStore()), + ) + assert ctrl_host._pending_applied_task_receipt(base_proposal) == { + "goal_id": "goal-a", + "todo_id": "todo-1", + "session_id": "sess-1", + "turn_id": "turn-1", + } + + # Dispatched / non-matching cases fail closed cleanly. + turn_record = {**turn_record, "upstream_turn_id": "up-1"} + assert host._pending_applied_task_receipt(base_proposal) is None + assert "task_execution_dispatch_pending" not in host.project_task_dispatch(base_proposal) + + turn_record = {"session_id": "sess-1", "turn_id": "turn-1", "client_turn_id": "task-start-prop-1", "status": "queued"} + for bad in ( + {**base_proposal, "context": {"binding_id": "bind-1"}}, + {**base_proposal, "normalized_parameters": {"goal_id": "goal-a", "start_execution": False}}, + {**base_proposal, "expected_state_fingerprint": "stale-fp"}, + {**base_proposal, "permission_classification": "protected"}, + ): + assert host._pending_applied_task_receipt(bad) is None + + err_host = _StubTodoHost( + registry_path=tmp_path / "registry.json", + chat_store=_TurnStore(raise_error=ValueError("corrupt")), + ) + assert err_host._pending_applied_task_receipt(base_proposal) is None + + +def test_canonical_basis_toctou_and_reviewed_edit_recovery( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + source_a = ChatTodoSource(tmp_path / "reg.json", tmp_path, "src-1", "sha-1", {"id": "goal-a"}) + source_b = ChatTodoSource(tmp_path / "reg.json", tmp_path, "src-2", "sha-1", {"id": "goal-a"}) + sources = iter([source_a, source_b]) + monkeypatch.setattr(todo_action_updates, "resolve_chat_todo_source", lambda host, gid: next(sources)) + monkeypatch.setattr( + todo_action_updates, + "read_canonical_todos_if_promoted", + lambda **kwargs: {"provider_revision": "r1", "source_authority": "sqlite", "todos": []}, + ) + host = _StubTodoHost(registry_path=tmp_path / "reg.json") + with pytest.raises(ValueError, match="registration changed while reading"): + host._canonical_update_basis("goal-a") + + monkeypatch.setattr(todo_action_updates, "resolve_chat_todo_source", lambda host, gid: source_a) + monkeypatch.setattr( + todo_action_updates, + "read_canonical_todos_if_promoted", + lambda **kwargs: { + "provider_revision": "r2", + "source_authority": "sqlite", + "todos": [{"todo_id": "t-user", "role": "user"}, {"todo_id": "t-agent", "role": "agent"}], + }, + ) + user_basis = _as_map(host._canonical_update_basis("goal-a", completion_todo_id="t-user")) + assert user_basis["schema_version"] == todo_action_contracts.CANONICAL_UPDATE_BASIS_SCHEMA_VERSION + agent_basis = _as_map(host._canonical_update_basis("goal-a", completion_todo_id="t-agent")) + assert agent_basis["schema_version"] == todo_action_contracts.CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION + dec_basis = _as_map(host._canonical_update_basis("goal-a", completion_todo_id="t-user", decision=True)) + assert dec_basis["schema_version"] == todo_action_contracts.CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION + + # Malformed non-None basis must fail closed instead of falling back to None. + with pytest.raises(ValueError, match="canonical update review basis is malformed"): + host._apply_reviewed_todo_edit( + "prop-bad", + {"action_kind": "todo.update", "expected_state_fingerprint": "fp", "canonical_update_basis": "bad"}, + {"goal_id": "goal-a", "todo_id": "t-1"}, + ) + + proposal: dict[str, object] = { + "action_kind": "todo.update", + "expected_state_fingerprint": "fp-orig", + "canonical_update_basis": { + "schema_version": todo_action_contracts.CANONICAL_UPDATE_BASIS_SCHEMA_VERSION, + "provider_revision": "r1", + "registry_sha256": "sha-1", + "source_authority": "sqlite", + }, + } + params: dict[str, object] = {"goal_id": "goal-a", "todo_id": "todo-1", "operation": "edit"} + + def raise_source_changed(*args: object, **kwargs: object) -> dict[str, object]: + raise ChatTodoSourceChanged("moved source") + + monkeypatch.setattr(host, "_run_todo_update", raise_source_changed) + res_changed = host._apply_reviewed_todo_edit("prop-1", proposal, params) + assert _as_map(_as_map(res_changed["proposal"])["failure"])["error_code"] == "canonical_update_source_changed" + + def raise_in_progress(*args: object, **kwargs: object) -> dict[str, object]: + raise LocalCoordinationAuthorityUnavailable("busy", code=COMPLETION_VALIDATION_IN_PROGRESS, payload={}) + + monkeypatch.setattr(host, "_run_todo_update", raise_in_progress) + with pytest.raises(ActionConflictError, match="busy"): + host._apply_reviewed_todo_edit("prop-2", proposal, params) + + def raise_validation_source_changed(*args: object, **kwargs: object) -> dict[str, object]: + raise LocalCoordinationAuthorityUnavailable( + "changed", + code="authority_source_changed", + payload={"completion_validation_executed": True}, + ) + + monkeypatch.setattr(host, "_run_todo_update", raise_validation_source_changed) + with pytest.raises(ValueError, match="during completion validation"): + host._apply_reviewed_todo_edit("prop-3", proposal, {**params, "operation": "complete"}) + assert host.store.failed[-1][1] == "canonical_update_validation_source_changed" + + def raise_conflict(*args: object, **kwargs: object) -> dict[str, object]: + raise LocalCoordinationAuthorityUnavailable("stale", code="provider_revision_mismatch", payload={}) + + monkeypatch.setattr(host, "_run_todo_update", raise_conflict) + stale_res = host._apply_reviewed_todo_edit("prop-4", proposal, params) + stale_prop = _as_map(stale_res["proposal"]) + assert stale_prop["status"] == "stale" + assert stale_prop["expected_state_fingerprint"] == _canonical_digest( + {"expected": "fp-orig", "conflict": "provider_revision_mismatch"} + ) + + monkeypatch.setattr(host, "_run_todo_update", lambda *a, **kw: {"ok": False, "reason_code": "test_fail"}) + val_fail = host._apply_reviewed_todo_edit("prop-5", proposal, params) + assert _as_map(_as_map(val_fail["proposal"])["failure"])["error_code"] == "canonical_update_validation_failed" + + monkeypatch.setattr( + host, + "_run_todo_update", + lambda *a, **kw: {"ok": True, "todo_id": "todo-1", "changed": True, "projection_delivery": "pending", "status": "open"}, + ) + proj_pending = host._apply_reviewed_todo_edit("prop-6", proposal, params) + assert _as_map(_as_map(proj_pending["proposal"])["failure"])["error_code"] == "canonical_update_projection_pending" + assert host.store.checkpoints[-1][1] == "canonical_update" + + host.monitor_runner = lambda *a, **kw: { + "ok": True, + "todo_id": "mon-1", + "original_receipt": {"changed": True}, + "projection_delivery": "delivered", + "provider_status": "paused", + } + mon_res = host._apply_reviewed_todo_edit( + "prop-7", + {**proposal, "action_kind": "monitor.update"}, + {"goal_id": "goal-a", "todo_id": "mon-1", "operation": "pause"}, + ) + assert _as_map(_as_map(mon_res["proposal"])["receipt"])["outcome"] == "monitor_paused" + + monkeypatch.setattr( + host, + "_run_gate_resolve", + lambda *a, **kw: { + "ok": True, + "todo_id": "gate-1", + "changed": True, + "projection_delivery": "current", + "status": "done", + "decision_outcome": "approved", + "unblock_resume": {"state": "queued"}, + }, + ) + gate_res = host._apply_reviewed_todo_edit( + "prop-8", + {**proposal, "action_kind": "gate.resolve"}, + {"goal_id": "goal-a", "todo_id": "gate-1", "decision": "approved"}, + ) + gate_receipt = _as_map(_as_map(gate_res["proposal"])["receipt"]) + assert gate_receipt["outcome"] == "gate_resolved" + assert gate_receipt["decision_outcome"] == "approved" + assert gate_receipt["unblock_resume_state"] == "queued" + + +def test_read_task_start_and_recover_applied_task_negatives( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + class _SessionFake: + def __init__( + self, + sessions: dict[str, dict[str, object]], + turns: dict[tuple[str, str], dict[str, object]], + ) -> None: + self.sessions = sessions + self.turns = turns + + def load_session(self, session_id: str) -> dict[str, object] | None: + return self.sessions.get(session_id) + + def load_turn(self, session_id: str, turn_id: str) -> dict[str, object] | None: + for item in self.turns.values(): + if item.get("session_id") == session_id and item.get("turn_id") == turn_id: + return item + return None + + def turn_for_client(self, session_id: str, client_turn_id: str) -> dict[str, object] | None: + return self.turns.get((session_id, client_turn_id)) + + def session_candidates( + self, + *, + goal_id: str | None, + agent_id: str, + channel_id: str | None = None, + ) -> list[dict[str, object]]: + return [ + row + for row in self.sessions.values() + if row.get("goal_id") == goal_id and row.get("agent_id") == agent_id and row.get("channel_id") == channel_id + ] + + chat = _SessionFake( + sessions={ + "s1": {"session_id": "s1", "goal_id": "goal-a", "agent_id": "codex", "channel_id": "task.todo-1"}, + "s2": {"session_id": "s2", "goal_id": "goal-a", "agent_id": "codex", "channel_id": "task.todo-1"}, + }, + turns={("s2", "task-start-p1"): {"session_id": "s2", "turn_id": "t2", "message": "do task"}}, + ) + with pytest.raises(ValueError, match="original Task Session is unavailable"): + ChatTodoActionMixin._read_task_start( + chat, + goal_id="goal-a", + agent_id="other-agent", + channel_id="task.todo-1", + client_turn_id="task-start-p1", + checkpoint={"session_id": "s1"}, + ) + sess, turn = ChatTodoActionMixin._read_task_start( + chat, + goal_id="goal-a", + agent_id="codex", + channel_id="task.todo-1", + client_turn_id="task-start-p1", + checkpoint=None, + ) + assert sess is not None and sess["session_id"] == "s2" and turn is not None and turn["turn_id"] == "t2" + + # Ambiguous multi-session candidate set with zero client turn matches fails closed. + chat.turns.clear() + with pytest.raises(ValueError, match="original Task Session is ambiguous"): + ChatTodoActionMixin._read_task_start( + chat, + goal_id="goal-a", + agent_id="codex", + channel_id="task.todo-1", + client_turn_id="task-start-missing", + checkpoint=None, + ) + + # read_confirmed_task detects turn message mutation and missing execution turn. + chat.turns[("s1", "task-start-p1")] = {"session_id": "s1", "turn_id": "t1", "message": "tampered"} + host = _StubTodoHost(registry_path=tmp_path / "reg.json", chat_store=chat) + with pytest.raises(ValueError, match="original Task Turn request changed"): + host._read_confirmed_task( + "p1", + {"goal_id": "goal-a", "agent_id": "codex", "text": "do task"}, + "todo-1", + {"task_session_opened": {"session_id": "s1"}}, + ) + + # recover_applied_task falls back cleanly to _turn_from_receipt when not pending dispatch. + assert host._recover_applied_task({"status": "applied", "receipt": {"turn": "x"}}) == {"turn_id": "turn-from-receipt"} + + # Mismatched todo_created checkpoint triggers explicit failure instead of guessing. + queued_turn: dict[str, object] = { + "session_id": "s1", + "turn_id": "t1", + "client_turn_id": "task-start-p1", + "status": "queued", + } + chat.turns[("s1", "task-start-p1")] = queued_turn + monkeypatch.setattr( + todo_action_tasks, + "resolve_chat_todo_source", + lambda *a, **kw: ChatTodoSource(tmp_path / "reg.json", tmp_path, "src-1", "sha-1", {"id": "goal-a"}), + ) + bad_recovery_proposal: dict[str, object] = { + "proposal_id": "p1", + "status": "applied", + "action_kind": "todo.create", + "permission_classification": "durable_write", + "expected_state_fingerprint": "prev-1", + "context": {}, + "normalized_parameters": {"goal_id": "goal-a", "agent_id": "codex", "start_execution": True}, + "checkpoint": {"steps": {"todo_created": {"todo_id": "wrong-todo", "canonical_receipt": {}}}}, + "receipt": { + "outcome": "task_execution_started", + "projection_verified": True, + "resource_ids": {"goal_id": "goal-a", "todo_id": "todo-1", "session_id": "s1", "turn_id": "t1"}, + "canonical_receipt": {"goal_id": "goal-a", "todo_id": "todo-1", "status": "applied", "preview_id": "prev-1"}, + }, + } + with pytest.raises(ValueError, match="creation checkpoint changed"): + host._recover_applied_task(bad_recovery_proposal) + assert callable(todo_action_create.apply_todo_create) + assert callable(todo_actions._decision_readback)