diff --git a/loopx/chat/action_store_common.py b/loopx/chat/action_store_common.py new file mode 100644 index 0000000000..57f6e3e304 --- /dev/null +++ b/loopx/chat/action_store_common.py @@ -0,0 +1,655 @@ +"""Shared Zero-Any schema, validation, and lock helpers for Chat action persistence.""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from contextlib import contextmanager +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +import re +from typing import Protocol, TypeAlias, TypeGuard + +from ..public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID + +JsonPrimitive: TypeAlias = None | bool | int | float | str +JsonValue: TypeAlias = JsonPrimitive | list["JsonValue"] | dict[str, "JsonValue"] +JsonDict: TypeAlias = dict[str, object] +ObjectDict: TypeAlias = dict[str, object] + +CHAT_ACTION_STORE_SCHEMA_VERSION = "loopx_chat_action_store_v1" +CHAT_ACTION_PROPOSAL_SCHEMA_VERSION = "loopx_chat_action_proposal_v1" +HUMAN_ACTOR_CLASS = "human" +AUTHENTICATED_LARK_CARD_CALLBACK = "lark_authenticated_card_callback_v1" + +PROPOSAL_STATES = { + "preview_ready", + "applying", + "gated", + "failed", + "rejected", + "deferred", + "cancelled", + "stale", + "applied", +} +RETRYABLE_PROPOSAL_STATES = {"preview_ready", "gated", "failed", "deferred"} + +OPERATION_ENVELOPE_SCHEMA_VERSION = "loopx_operation_envelope_v0" +OPERATION_LIFECYCLE_STATES = { + "awaiting_confirmation", + "claimed", + "outcome_observed", +} + +_LOCAL_PATH = re.compile( + r"(?:^|[\s\"'])(?:/Users/|/home/|/private/|/var/folders/|/tmp/|~[/\\]|file://)", + re.IGNORECASE, +) +_SENSITIVE_TEXT = re.compile( + r"(?:bearer\s+[A-Za-z0-9._~+/-]+|sk-[A-Za-z0-9_-]{4,}|raw\s+(?:provider|tool)\s+(?:payload|output))", + re.IGNORECASE, +) +_SENSITIVE_KEYS = { + "api_key", + "apikey", + "authorization", + "auth_token", + "access_token", + "refresh_token", + "password", + "passwd", + "secret", + "credentials", + "credential", + "private_key", + "raw_provider_payload", + "provider_payload", + "raw_tool_output", + "tool_output", + "stderr", + "command", +} + + +class ActionConflictError(RuntimeError): + """Raised when a typed action transition conflicts with durable state.""" + + +class ActionStoreBackend(Protocol): + """Minimal storage contract satisfied by ChatActionStore.""" + + path: Path + + def _read(self) -> JsonDict: ... + + def _write(self, payload: JsonDict) -> None: ... + + +def _utc_now() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _opaque_id(value: object, *, field: str) -> str: + token = str(value or "").strip() + if not _OPAQUE_ID.fullmatch(token): + raise ValueError(f"{field} must be a compact opaque id") + return token + + +def normalize_idempotency_key(value: object) -> str: + """Return the canonical token this store binds and persists.""" + return _opaque_id(value, field="idempotency_key") + + +def _bounded_text(value: object, *, field: str, limit: int = 4000) -> str: + text = str(value or "").strip() + if not text or len(text) > limit or any(ord(character) < 32 for character in text): + raise ValueError(f"{field} must be bounded visible text") + return text + + +def _safe_json_value(value: object, *, path: str = "payload") -> JsonValue: + """Recursively validate and clone JSON-compatible public-safe values.""" + if value is None or isinstance(value, (bool, int)): + return value + if isinstance(value, float): + if not math.isfinite(value): + raise ValueError(f"{path} must contain finite JSON numbers") + return value + if isinstance(value, str): + if _LOCAL_PATH.search(value) or _SENSITIVE_TEXT.search(value): + raise ValueError(f"{path} contains sensitive material") + if len(value) > 8000 or any(ord(character) < 9 for character in value): + raise ValueError(f"{path} must contain bounded public-safe text") + return value + if isinstance(value, Mapping): + safe: dict[str, JsonValue] = {} + for raw_key, item in value.items(): + key = str(raw_key).strip() + normalized_key = re.sub(r"[^a-z0-9]+", "_", key.lower()).strip("_") + if not key or normalized_key in _SENSITIVE_KEYS: + raise ValueError(f"{path}.{key or ''} is a sensitive field") + safe[key] = _safe_json_value(item, path=f"{path}.{key}") + return safe + if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray)): + return [ + _safe_json_value(item, path=f"{path}[{index}]") + for index, item in enumerate(value) + ] + raise ValueError(f"{path} must be JSON-compatible") + + +def _canonical_digest(payload: Mapping[str, object]) -> str: + encoded = json.dumps( + payload, + allow_nan=False, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def is_str_dict(value: object) -> TypeGuard[JsonDict]: + """Narrow an arbitrary object to a string-keyed mutable dictionary.""" + return isinstance(value, dict) and all(isinstance(key, str) for key in value) + + +def require_str_dict(value: object, *, error: str) -> JsonDict: + """Return a validated string-keyed dict or raise ValueError.""" + if not is_str_dict(value): + raise ValueError(error) + return value + + +def safe_object_dict( + value: Mapping[str, object], *, path: str, label: str +) -> JsonDict: + """Sanitize a mapping and preserve its mutable string-keyed dict contract.""" + safe = _safe_json_value(dict(value), path=path) + if not is_str_dict(safe): + raise ValueError(f"{label} must be an object") + return safe + + +def validate_safe_object( + value: Mapping[str, object], + *, + path: str, + label: str, + required_keys: frozenset[str] | set[str] | None = None, + allowed_extra_keys: frozenset[str] | set[str] = frozenset(), + bounded_fields: Iterable[str] = (), + field_prefix: str = "", + fields_error: str | None = None, +) -> JsonDict: + """Validate a public-safe object payload, key set, and bounded text fields.""" + safe = safe_object_dict(value, path=path, label=label) + if required_keys is not None: + actual_keys = set(safe) + allowed_keys = set(required_keys) | set(allowed_extra_keys) + if not (set(required_keys) <= actual_keys <= allowed_keys): + raise ValueError(fields_error or f"{label} has unsupported or missing fields") + prefix = field_prefix or path + for field in bounded_fields: + _bounded_text(safe.get(field), field=f"{prefix}.{field}", limit=512) + return safe + + +def validate_decision(decision: str, *, label: str) -> str: + """Validate a human confirmation decision token.""" + selected = str(decision or "").strip().lower() + if selected not in {"confirm", "reject"}: + raise ValueError(f"{label} decision must be confirm or reject") + return selected + + +def validate_human_confirmation( + confirmation: Mapping[str, object], + *, + path: str, + label: str, + required_keys: frozenset[str], +) -> JsonDict: + """Validate common human-verified callback envelope invariants.""" + safe = validate_safe_object( + confirmation, + path=path, + label=label, + required_keys=required_keys, + bounded_fields=required_keys, + field_prefix=path, + ) + if safe["actor_class"] != HUMAN_ACTOR_CLASS: + raise ValueError(f"{label} requires a human actor") + _opaque_id(safe["verification_kind"], field=f"{path}.verification_kind") + return safe + + +def parse_utc_timestamp(value: object, *, error: str) -> datetime: + """Parse an ISO timestamp and enforce an explicit timezone offset.""" + parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError(error) + return parsed + + +def current_utc_now() -> str: + """Read `_utc_now` through `loopx.chat_action_store` so monkeypatches apply.""" + from .. import chat_action_store as facade + + return facade._utc_now() + + +@contextmanager +def store_lock( + path: Path, + *, + operation: str, + agent_id: str | None = "loopx-chat", +) -> Iterator[Path]: + """Acquire `exclusive_file_lock` through `loopx.chat_action_store`.""" + from .. import chat_action_store as facade + + if agent_id is None: + with facade.exclusive_file_lock(path, operation=operation) as locked: + yield locked + return + with facade.exclusive_file_lock( + path, agent_id=agent_id, operation=operation + ) as locked: + yield locked + + +def store_proposals(payload: JsonDict) -> JsonDict: + """Extract the top-level proposals map from a validated store payload.""" + return require_str_dict( + payload.get("proposals"), error="typed Chat action store is malformed" + ) + + +def store_idempotency(payload: JsonDict) -> JsonDict: + """Extract the top-level idempotency index from a validated store payload.""" + return require_str_dict( + payload.get("idempotency"), error="typed Chat action store is malformed" + ) + + +def require_proposal( + payload: JsonDict, + token: str, + *, + message: str = "typed Chat action proposal was not found", +) -> JsonDict: + """Load one proposal dict by token or raise KeyError.""" + proposal = store_proposals(payload).get(token) + if not is_str_dict(proposal): + raise KeyError(message) + return proposal + + +def require_operation(payload: JsonDict, token: str) -> tuple[JsonDict, JsonDict]: + """Load a proposal and its operation envelope, raising KeyError if absent.""" + proposal = store_proposals(payload).get(token) + operation = proposal.get("operation") if is_str_dict(proposal) else None + if not is_str_dict(proposal) or not is_str_dict(operation): + raise KeyError("typed operation was not found") + return proposal, operation + + +def commit_proposal_mutation( + store: ActionStoreBackend, + payload: JsonDict, + proposal: JsonDict, + *, + updated_at: str | None = None, +) -> JsonDict: + """Stamp `updated_at`, persist the store payload, and return the proposal.""" + proposal["updated_at"] = updated_at if updated_at is not None else current_utc_now() + store._write(payload) + return proposal + + +def is_agent_operation_executor(proposal: Mapping[str, object]) -> bool: + """Return whether a proposal's normalized executor uses agent handoff.""" + parameters = proposal.get("normalized_parameters") + if not is_str_dict(parameters): + return False + executor = parameters.get("executor") + return is_str_dict(executor) and executor.get("kind") in { + "agent_session", + "managed_turn", + } + + +def operation_confirmation_digest( + proposal: Mapping[str, object], parameters: Mapping[str, object] +) -> str: + """Compute the canonical confirmation digest for an operation.execute request.""" + return _canonical_digest( + { + "action_kind": "operation.execute", + "normalized_parameters": parameters, + "request_digest": proposal.get("request_digest"), + } + ) + + +def _matching_pending_preview( + proposals: Mapping[str, object], + *, + action_kind: str, + context: Mapping[str, object], + normalized_parameters: Mapping[str, object], + shared_fields: tuple[str, ...], + reusable_states: set[str], + matches_review_basis: Callable[[object], bool], +) -> JsonDict | None: + candidates: list[JsonDict] = [] + for row in proposals.values(): + if not is_str_dict(row) or row.get("status") not in reusable_states: + continue + row_context = row.get("context") + if ( + row.get("action_kind") != action_kind + or not is_str_dict(row_context) + or any(row_context.get(field) != value for field, value in context.items()) + ): + continue + row_params = row.get("normalized_parameters") + if not is_str_dict(row_params): + continue + if any( + row_params.get(field) != normalized_parameters[field] + for field in shared_fields + ): + continue + if not matches_review_basis(row.get("expected_state_fingerprint")): + continue + candidates.append(row) + return max( + candidates, + key=lambda row: ( + str(row.get("updated_at") or ""), + str(row.get("proposal_id") or ""), + ), + default=None, + ) + + +def replay_or_reuse_preview( + store: ActionStoreBackend, + *, + action_kind: str, + context: Mapping[str, object], + normalized_parameters: Mapping[str, object], + idempotency_key: str, + shared_fields: tuple[str, ...], + reusable_states: set[str], + matches_review_basis: Callable[[object], bool] | None = None, + require_exact_context: bool = False, + summary: str | None = None, +) -> JsonDict | None: + """Resolve an accepted request or bind it to an equivalent pending review.""" + if summary is not None: + _safe_json_value( + _bounded_text(summary, field="summary"), path="preview.summary" + ) + key = normalize_idempotency_key(idempotency_key) + request = safe_object_dict( + { + "action_kind": action_kind, + "context": context, + "normalized_parameters": normalized_parameters, + }, + path="payload", + label="preview", + ) + digest = _canonical_digest(request) + + with store_lock(store.path, operation="reuse_chat_action_preview"): + payload = store._read() + proposals = store_proposals(payload) + bindings = store_idempotency(payload) + if key in bindings: + binding = bindings[key] + bound_id = binding.get("proposal_id") if is_str_dict(binding) else None + row = proposals.get(bound_id) if isinstance(bound_id, str) else None + if not is_str_dict(binding) or not is_str_dict(row): + raise ValueError( + "typed Chat action idempotency index is inconsistent" + ) + previous_digest = binding.get("reused_request_digest") + if previous_digest is not None: + same_request = previous_digest == digest + else: + same_request = row.get("normalized_parameters") == request.get( + "normalized_parameters" + ) and ( + not require_exact_context + or row.get("context") == request.get("context") + ) + row_context = row.get("context") + matches_scope = ( + row.get("action_kind") == action_kind + and is_str_dict(row_context) + and all( + row_context.get(field) == value for field, value in context.items() + ) + ) + if not matches_scope or not same_request: + raise ActionConflictError( + "idempotency key already belongs to another preview" + ) + return row + + if not reusable_states or matches_review_basis is None: + return None + pending = _matching_pending_preview( + proposals, + action_kind=action_kind, + context=context, + normalized_parameters=normalized_parameters, + shared_fields=shared_fields, + reusable_states=reusable_states, + matches_review_basis=matches_review_basis, + ) + if pending is None: + return None + bindings[key] = { + "proposal_id": pending["proposal_id"], + "reused_request_digest": digest, + } + store._write(payload) + return pending + + +def list_proposals( + store: ActionStoreBackend, + *, + goal_id: str | None = None, + context_kind: str | None = None, + status: str | None = None, +) -> list[JsonDict]: + """List valid stored proposals ordered newest-first.""" + selected_goal = _opaque_id(goal_id, field="goal_id") if goal_id else None + selected_context = ( + _opaque_id(context_kind, field="context_kind") if context_kind else None + ) + if status and status not in PROPOSAL_STATES: + raise ValueError("status must be a supported typed action state") + proposals: list[JsonDict] = [] + for raw in store_proposals(store._read()).values(): + if not is_str_dict(raw) or raw.get("status") not in PROPOSAL_STATES: + continue + raw_context = raw.get("context") + context = raw_context if is_str_dict(raw_context) else {} + raw_params = raw.get("normalized_parameters") + parameters = raw_params if is_str_dict(raw_params) else {} + proposal_goal = str( + context.get("goal_id") or parameters.get("goal_id") or "" + ) + if selected_goal and proposal_goal != selected_goal: + continue + if selected_context and str(context.get("kind") or "") != selected_context: + continue + if status and raw.get("status") != status: + continue + proposals.append(raw) + return sorted( + proposals, + key=lambda proposal: ( + str(proposal.get("updated_at") or ""), + str(proposal.get("proposal_id") or ""), + ), + reverse=True, + ) + + +def cancel_proposal(store: ActionStoreBackend, proposal_id: str) -> JsonDict: + """Cancel an awaiting/retryable proposal and any armed operation envelope.""" + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="cancel_chat_action_preview"): + payload = store._read() + proposal = require_proposal(payload, token) + if proposal.get("status") == "cancelled": + return proposal + if proposal.get("status") not in { + "preview_ready", + "gated", + "failed", + "deferred", + }: + raise ActionConflictError( + f"proposal in {proposal.get('status')} state cannot be cancelled" + ) + now = current_utc_now() + proposal["status"] = "cancelled" + proposal["cancelled_at"] = now + operation = proposal.get("operation") + if is_str_dict(operation): + outcome: JsonDict = { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "cancelled_before_confirmation", + "projection_verified": True, + "observed_at": now, + } + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = outcome + proposal["receipt"] = outcome + proposal["gate"] = None + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def save_proposal_checkpoint( + store: ActionStoreBackend, + proposal_id: str, + *, + step: str, + receipt: Mapping[str, object], +) -> JsonDict: + """Persist one completed step receipt inside an active/recoverable proposal.""" + safe_step = _opaque_id(step, field="step") + safe_receipt = safe_object_dict( + receipt, path="checkpoint.receipt", label="checkpoint receipt" + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="checkpoint_chat_action_preview"): + payload = store._read() + proposal = require_proposal(payload, token) + if proposal.get("status") not in {"applying", "gated", "failed"}: + raise ActionConflictError( + f"proposal in {proposal.get('status')} state cannot save a checkpoint" + ) + raw_checkpoint = proposal.get("checkpoint") + checkpoint: JsonDict = ( + dict(raw_checkpoint) if is_str_dict(raw_checkpoint) else {"steps": {}} + ) + raw_steps = checkpoint.get("steps") + steps: JsonDict = dict(raw_steps) if is_str_dict(raw_steps) else {} + steps[safe_step] = safe_receipt + now = current_utc_now() + checkpoint["steps"] = steps + checkpoint["last_completed_step"] = safe_step + checkpoint["updated_at"] = now + proposal["checkpoint"] = checkpoint + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def transition_proposal( + store: ActionStoreBackend, + proposal_id: str, + *, + from_states: set[str], + to_state: str, + updates: Mapping[str, object], + idempotent_states: set[str], +) -> JsonDict: + """Atomically move one proposal across validated lifecycle states.""" + token = _opaque_id(proposal_id, field="proposal_id") + if to_state not in PROPOSAL_STATES: + raise ValueError("unsupported typed action state") + with store_lock(store.path, operation=f"transition_chat_action_{to_state}"): + payload = store._read() + proposal = require_proposal(payload, token) + status = str(proposal.get("status") or "") + if status in idempotent_states: + return proposal + if status not in from_states: + raise ActionConflictError( + f"proposal in {status} state cannot become {to_state}" + ) + proposal["status"] = to_state + proposal.update( + safe_object_dict(updates, path="transition", label="transition") + ) + return commit_proposal_mutation(store, payload, proposal) + + +def apply_proposal( + store: ActionStoreBackend, + proposal_id: str, + *, + current_state_fingerprint: str, + receipt: Mapping[str, object], +) -> JsonDict: + """Commit one applied receipt or mark the proposal stale on fingerprint drift.""" + token = _opaque_id(proposal_id, field="proposal_id") + current_fingerprint = _bounded_text( + current_state_fingerprint, + field="current_state_fingerprint", + limit=512, + ) + with store_lock(store.path, operation="apply_chat_action_preview"): + payload = store._read() + proposal = require_proposal(payload, token) + status = str(proposal.get("status") or "") + if status == "applied": + return proposal + if status not in {"preview_ready", "applying"}: + raise ActionConflictError( + f"proposal in {status} state cannot be applied" + ) + expected_fingerprint = str(proposal.get("expected_state_fingerprint") or "") + now = current_utc_now() + if current_fingerprint != expected_fingerprint: + proposal["status"] = "stale" + proposal["stale"] = { + "expected_state_fingerprint": expected_fingerprint, + "current_state_fingerprint": current_fingerprint, + "detected_at": now, + } + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + safe_receipt = safe_object_dict(receipt, path="receipt", label="receipt") + _opaque_id(safe_receipt.get("receipt_id"), field="receipt.receipt_id") + _opaque_id(safe_receipt.get("outcome"), field="receipt.outcome") + if safe_receipt.get("projection_verified") is not True: + raise ValueError("receipt.projection_verified must be true") + proposal["status"] = "applied" + proposal["receipt"] = safe_receipt + proposal["applied_at"] = now + return commit_proposal_mutation(store, payload, proposal, updated_at=now) diff --git a/loopx/chat/action_store_operations.py b/loopx/chat/action_store_operations.py new file mode 100644 index 0000000000..f2a7ce4c54 --- /dev/null +++ b/loopx/chat/action_store_operations.py @@ -0,0 +1,597 @@ +"""Operation envelope confirmation, agent handoff, and delivery persistence.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from datetime import datetime, timedelta +import uuid + +from .action_store_common import ( + OPERATION_ENVELOPE_SCHEMA_VERSION, + OPERATION_LIFECYCLE_STATES, + ActionConflictError, + ActionStoreBackend, + JsonDict, + _canonical_digest, + _opaque_id, + commit_proposal_mutation, + current_utc_now, + is_agent_operation_executor, + is_str_dict, + operation_confirmation_digest, + parse_utc_timestamp, + require_operation, + require_proposal, + require_str_dict, + safe_object_dict, + store_lock, + store_proposals, + validate_decision, + validate_human_confirmation, + validate_safe_object, +) + +_OPERATION_DELIVERY_FIELDS = ( + "provider", + "message_id", + "chat_id", + "app_id", + "binding_digest", + "card_digest", + "delivered_at", +) +_OPERATION_CONFIRMATION_FIELDS = frozenset( + { + "provider", + "event_id", + "principal", + "message_id", + "chat_id", + "app_id", + "surface_kind", + "interaction_kind", + "confirmation_digest", + "card_digest", + "confirmed_at", + "actor_class", + "verification_kind", + } +) +_OPERATION_RESULT_FIELDS = frozenset( + { + "provider", + "message_id", + "chat_id", + "app_id", + "card_digest", + "transport", + "delivered_at", + } +) + + +def _list_from_sequence_or_empty(value: object) -> list[object]: + if value is None: + return [] + if isinstance(value, Iterable) and not isinstance(value, (str, bytes, bytearray)): + return list(value) + raise ValueError("authorized_principals must be a sequence") + + +def arm_operation(store: ActionStoreBackend, proposal_id: str) -> JsonDict: + """Turn one provider-neutral preview into the canonical confirmation gate. + + The immutable request already lives on the proposal. This method adds + only lifecycle state derived from that request; Lark, the Dashboard and + domain executors must all read this same envelope. + """ + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="arm_operation_confirmation"): + payload = store._read() + proposal = require_proposal(payload, token) + if proposal.get("action_kind") != "operation.execute": + raise ActionConflictError("only operation.execute previews can be armed") + existing = proposal.get("operation") + if is_str_dict(existing): + if ( + existing.get("schema_version") != OPERATION_ENVELOPE_SCHEMA_VERSION + or existing.get("lifecycle_state") not in OPERATION_LIFECYCLE_STATES + ): + raise ValueError("typed operation envelope is malformed") + return proposal + if proposal.get("status") != "preview_ready": + raise ActionConflictError( + f"proposal in {proposal.get('status')} state cannot await confirmation" + ) + parameters = proposal.get("normalized_parameters") + if not is_str_dict(parameters): + raise ValueError("typed operation parameters are malformed") + now = current_utc_now() + executor = parameters.get("executor") + operation: JsonDict = { + "schema_version": OPERATION_ENVELOPE_SCHEMA_VERSION, + "operation_id": token, + "lifecycle_state": "awaiting_confirmation", + "confirmation_digest": operation_confirmation_digest(proposal, parameters), + "payload_digest": parameters.get("payload_digest"), + "projection_digest": parameters.get("projection_digest"), + "executor_revision": ( + executor.get("revision") if is_str_dict(executor) else None + ), + "destination_account_ref": parameters.get("destination_account_ref"), + "expires_at": parameters.get("expires_at"), + "authorized_principals": _list_from_sequence_or_empty( + parameters.get("authorized_principals") + ), + "delivery": None, + "confirmation": None, + "claim": None, + "outcome": None, + "result_delivery": None, + "armed_at": now, + } + proposal["operation"] = safe_object_dict( + operation, path="operation", label="operation" + ) + proposal["status"] = "gated" + proposal["gate"] = { + "kind": "human_operation_confirmation", + "summary": "This exact operation is awaiting an authenticated human decision.", + "next_action": "Use the bound operation card; ordinary typed-action apply is not confirmation.", + } + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def record_operation_delivery( + store: ActionStoreBackend, + proposal_id: str, + *, + delivery: Mapping[str, object], +) -> JsonDict: + """Bind the exact provider message which may attest a later click.""" + safe_delivery = validate_safe_object( + delivery, + path="operation.delivery", + label="operation delivery", + bounded_fields=_OPERATION_DELIVERY_FIELDS, + field_prefix="operation.delivery", + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="record_operation_delivery"): + payload = store._read() + proposal, operation = require_operation(payload, token) + if operation.get("lifecycle_state") != "awaiting_confirmation": + existing = operation.get("delivery") + if is_str_dict(existing) and existing == safe_delivery: + return proposal + raise ActionConflictError("operation is no longer awaiting delivery") + existing = operation.get("delivery") + if existing is not None: + if existing != safe_delivery: + raise ActionConflictError( + "operation is already bound to another provider message" + ) + return proposal + operation["delivery"] = safe_delivery + return commit_proposal_mutation(store, payload, proposal) + + +def record_operation_delivery_snapshot( + store: ActionStoreBackend, + proposal_id: str, + *, + submitted_card: Mapping[str, object], +) -> JsonDict: + """Persist the immutable sent card after verifying its recorded digest.""" + safe_card = safe_object_dict( + submitted_card, + path="operation.delivery.submitted_card", + label="operation submitted card", + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="record_operation_delivery_snapshot"): + payload = store._read() + proposal = store_proposals(payload).get(token) + operation = ( + proposal.get("operation") if is_str_dict(proposal) else None + ) + delivery = operation.get("delivery") if is_str_dict(operation) else None + if not is_str_dict(proposal) or not is_str_dict(delivery): + raise ActionConflictError("operation card delivery was not recorded") + if _canonical_digest(safe_card) != delivery.get("card_digest"): + raise ActionConflictError("operation submitted card digest drifted") + existing = delivery.get("submitted_card") + if existing is not None: + if existing != safe_card: + raise ActionConflictError( + "operation submitted card snapshot already differs" + ) + return proposal + delivery["submitted_card"] = safe_card + return commit_proposal_mutation(store, payload, proposal) + + +def decide_operation( + store: ActionStoreBackend, + proposal_id: str, + *, + decision: str, + confirmation: Mapping[str, object], +) -> JsonDict: + """Atomically reject, or confirm and claim, one delivered operation. + + The transport owner must supply a verified callback envelope. A + successful confirmation consumes the operation in this transaction so + concurrent web/Lark clicks cannot both dispatch it. + """ + selected_decision = validate_decision(decision, label="operation") + safe_confirmation = validate_human_confirmation( + confirmation, + path="operation.confirmation", + label="operation confirmation", + required_keys=_OPERATION_CONFIRMATION_FIELDS, + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="decide_operation"): + payload = store._read() + proposal, operation = require_operation(payload, token) + existing_confirmation = operation.get("confirmation") + if is_str_dict(existing_confirmation): + if existing_confirmation.get("event_id") == safe_confirmation["event_id"]: + return proposal + raise ActionConflictError("operation already consumed another decision") + if ( + proposal.get("status") != "gated" + or operation.get("lifecycle_state") != "awaiting_confirmation" + ): + raise ActionConflictError("operation is not awaiting confirmation") + delivery = operation.get("delivery") + if not is_str_dict(delivery): + raise ActionConflictError("operation card delivery is not verified") + expected = { + "provider": delivery.get("provider"), + "message_id": delivery.get("message_id"), + "chat_id": delivery.get("chat_id"), + "app_id": delivery.get("app_id"), + "card_digest": delivery.get("card_digest"), + "confirmation_digest": operation.get("confirmation_digest"), + } + if any( + safe_confirmation.get(field) != value for field, value in expected.items() + ): + raise ActionConflictError( + "operation callback does not match the delivered request" + ) + principals = _list_from_sequence_or_empty( + operation.get("authorized_principals") + ) + if safe_confirmation.get("principal") not in set(principals): + raise ActionConflictError( + "principal is not authorized for this operation" + ) + expires_at = parse_utc_timestamp( + operation.get("expires_at"), + error="operation timestamps require a timezone", + ) + confirmed_at = parse_utc_timestamp( + safe_confirmation["confirmed_at"], + error="operation timestamps require a timezone", + ) + delivered_at = parse_utc_timestamp( + delivery.get("delivered_at"), + error="operation timestamps require a timezone", + ) + if confirmed_at < delivered_at - timedelta(minutes=5): + raise ActionConflictError( + "operation confirmation predates the delivered request" + ) + if confirmed_at > expires_at: + raise ActionConflictError("operation confirmation arrived after expiry") + now = current_utc_now() + now_at = datetime.fromisoformat(now.replace("Z", "+00:00")) + if confirmed_at > now_at + timedelta(minutes=5): + raise ActionConflictError( + "operation confirmation timestamp is in the future" + ) + operation["confirmation"] = { + **safe_confirmation, + "decision": selected_decision, + } + if selected_decision == "reject": + outcome: JsonDict = { + "schema_version": "loopx_operation_outcome_v0", + "outcome": "rejected_by_operator", + "projection_verified": True, + "observed_at": now, + } + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = outcome + proposal["status"] = "rejected" + proposal["rejected_at"] = now + proposal["receipt"] = outcome + else: + operation["lifecycle_state"] = "claimed" + operation["claim"] = { + "claim_id": "claim-" + uuid.uuid4().hex, + "event_id": safe_confirmation["event_id"], + "claimed_at": now, + } + proposal["status"] = "applying" + proposal["gate"] = None + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def agent_operation_plan( + proposal: Mapping[str, object], **request: object +) -> JsonDict: + """One typed decision, using the existing canonical JSON byte format.""" + from ..control_plane.effect_runtime import ( + EffectRuntimeRemoteError, + effect_runtime_result, + ) + + raw_params = proposal.get("normalized_parameters") + parameters = raw_params if is_str_dict(raw_params) else {} + raw_payload = parameters.get("payload") + payload_map = raw_payload if is_str_dict(raw_payload) else {} + raw_projection = parameters.get("projection") + projection_map = raw_projection if is_str_dict(raw_projection) else {} + raw_op = proposal.get("operation") + raw_outcome = raw_op.get("outcome") if is_str_dict(raw_op) else None + digests = { + "payload_digest": _canonical_digest(payload_map), + "projection_digest": _canonical_digest(projection_map), + "confirmation_digest": operation_confirmation_digest(proposal, parameters), + "outcome_digest": ( + _canonical_digest(raw_outcome) if is_str_dict(raw_outcome) else None + ), + } + try: + raw_plan: object = effect_runtime_result( + "operation.agent_handoff.plan", + { + "proposal": dict(proposal), + "digests": digests, + "now": current_utc_now(), + **request, + }, + ) + except EffectRuntimeRemoteError as exc: + raise ActionConflictError(str(exc)) from exc + if not is_str_dict(raw_plan): + raise ValueError("agent operation plan must be an object") + return dict(raw_plan) + + +def observe_operation_outcome( + store: ActionStoreBackend, + proposal_id: str, + *, + outcome: Mapping[str, object], + agent_actor: Mapping[str, object] | None = None, + agent_binding_current: bool = False, + agent_actor_binding_current: bool = False, +) -> JsonDict: + """Persist the domain result without making it a retryable submission.""" + safe_outcome = safe_object_dict( + outcome, path="operation.outcome", label="operation outcome" + ) + if safe_outcome.get("schema_version") != "loopx_operation_outcome_v0": + raise ValueError("operation outcome schema is unsupported") + _opaque_id(safe_outcome.get("outcome"), field="operation.outcome.outcome") + if safe_outcome.get("projection_verified") is not True: + raise ValueError("operation outcome projection must be verified") + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="observe_operation_outcome"): + payload = store._read() + proposal, operation = require_operation(payload, token) + report_provenance: object = None + if is_agent_operation_executor(proposal): + plan = agent_operation_plan( + proposal, + action="report", + actor=agent_actor, + binding_current=agent_binding_current, + actor_binding_current=agent_actor_binding_current, + outcome=safe_outcome, + ) + report_provenance = plan["report_provenance"] + if plan.get("write_reconciliation") is True: + existing = operation.get("reconciliation") + if existing is not None: + if existing != safe_outcome: + raise ActionConflictError( + "operation reconciliation is already immutable" + ) + return proposal + operation["reconciliation"] = safe_outcome + operation["reconciliation_report"] = report_provenance + proposal["receipt"] = safe_outcome + return commit_proposal_mutation(store, payload, proposal) + if operation.get("lifecycle_state") == "outcome_observed": + if operation.get("outcome") != safe_outcome: + raise ActionConflictError("operation outcome is already immutable") + return proposal + if ( + operation.get("lifecycle_state") != "claimed" + or proposal.get("status") != "applying" + ): + raise ActionConflictError("only a claimed operation can record an outcome") + now = current_utc_now() + operation["lifecycle_state"] = "outcome_observed" + operation["outcome"] = safe_outcome + if report_provenance is not None: + operation["outcome_report"] = report_provenance + proposal["status"] = "applied" + proposal["receipt"] = safe_outcome + proposal["applied_at"] = now + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def _apply_agent_operation_plan( + store: ActionStoreBackend, + proposal_id: str, + *, + lock_operation: str, + agent_id: str | None, + plan_request: JsonDict, + pop_key: str, + operation_field: str, +) -> tuple[JsonDict, object | None]: + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, agent_id=agent_id, operation=lock_operation): + payload = store._read() + proposal = require_proposal( + payload, token, message="typed operation was not found" + ) + plan = agent_operation_plan(proposal, **plan_request) + receipt = plan.pop(pop_key, None) + if receipt is not None: + operation = require_str_dict( + proposal.get("operation"), + error="typed operation envelope is malformed", + ) + operation[operation_field] = receipt + commit_proposal_mutation(store, payload, proposal) + return plan, receipt + + +def reserve_agent_operation_turn( + store: ActionStoreBackend, + proposal_id: str, + **launch_context: object, +) -> JsonDict: + """Internal callback launch intent. + + Commit before spawning. A lost/failed spawn is reconciled from the + original Turn; callback replay never launches a replacement process. + """ + plan, receipt = _apply_agent_operation_plan( + store, + proposal_id, + lock_operation="reserve_operation_turn", + agent_id=None, + plan_request={"action": "wake", **launch_context}, + pop_key="write_turn_launch", + operation_field="turn_launch", + ) + if receipt is not None: + plan["turn_launch"] = receipt + return plan + + +def record_agent_operation_host_start( + store: ActionStoreBackend, + proposal_id: str, + *, + actor: Mapping[str, object], + binding_current: bool, + turn_key: str, +) -> JsonDict: + """Internal native transport observation; never a caller proof or permit.""" + plan, receipt = _apply_agent_operation_plan( + store, + proposal_id, + lock_operation="observe_operation_host_start", + agent_id=None, + plan_request={ + "action": "observe_host_start", + "actor": dict(actor), + "binding_current": binding_current, + "turn_key": turn_key, + }, + pop_key="write_host_start", + operation_field="host_start", + ) + if receipt is not None: + plan.update(host_start=receipt, host_delivery="native_start_accepted") + return plan + + +def consume_agent_operation( + store: ActionStoreBackend, + proposal_id: str, + *, + actor: Mapping[str, object], + binding_current: bool, + consumption_id: str, +) -> JsonDict: + """Commit before external execution. Even an exact replay grants no retry.""" + plan, handoff = _apply_agent_operation_plan( + store, + proposal_id, + lock_operation="consume_agent_operation", + agent_id="loopx-chat", + plan_request={ + "action": "consume", + "actor": dict(actor), + "binding_current": binding_current, + "consumption_id": consumption_id, + }, + pop_key="write_handoff", + operation_field="agent_handoff", + ) + if is_str_dict(handoff): + plan["consumption_id"] = handoff["consumption_id"] + return plan + + +def record_operation_result_delivery( + store: ActionStoreBackend, + proposal_id: str, + *, + delivery: Mapping[str, object], +) -> JsonDict: + """Persist exact result-card readback without changing domain outcome.""" + safe_delivery = validate_safe_object( + delivery, + path="operation.result_delivery", + label="operation result delivery", + required_keys=_OPERATION_RESULT_FIELDS, + allowed_extra_keys={"outcome_stage"}, + bounded_fields=_OPERATION_RESULT_FIELDS, + field_prefix="operation.result_delivery", + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="record_operation_result_delivery"): + payload = store._read() + proposal, operation = require_operation(payload, token) + if operation.get("lifecycle_state") != "outcome_observed": + raise ActionConflictError( + "operation outcome is unavailable for result delivery" + ) + is_agent = is_agent_operation_executor(proposal) + expected_stage = ( + "reconciled" if operation.get("reconciliation") is not None else "initial" + ) + if is_agent and safe_delivery.get("outcome_stage") != expected_stage: + raise ActionConflictError( + "result delivery is not for the current operation outcome" + ) + if not is_agent and "outcome_stage" in safe_delivery: + raise ValueError( + "result outcome stage is only supported for Agent handoff" + ) + source_delivery = operation.get("delivery") + if not is_str_dict(source_delivery) or any( + safe_delivery.get(field) != source_delivery.get(field) + for field in ("provider", "message_id", "chat_id", "app_id") + ): + raise ActionConflictError( + "operation result delivery does not match the original card" + ) + existing = operation.get("result_delivery") + if is_str_dict(existing): + if existing != safe_delivery: + if not ( + is_agent + and existing.get("outcome_stage") == "initial" + and expected_stage == "reconciled" + ): + raise ActionConflictError( + "operation result delivery is already immutable" + ) + else: + return proposal + operation["result_delivery"] = safe_delivery + return commit_proposal_mutation(store, payload, proposal) diff --git a/loopx/chat/action_store_review_cards.py b/loopx/chat/action_store_review_cards.py new file mode 100644 index 0000000000..bf8163d565 --- /dev/null +++ b/loopx/chat/action_store_review_cards.py @@ -0,0 +1,305 @@ +"""Review-card delivery and multi-audience decision persistence for Chat actions.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +from .action_store_common import ( + ActionConflictError, + ActionStoreBackend, + JsonDict, + _canonical_digest, + _opaque_id, + commit_proposal_mutation, + current_utc_now, + is_str_dict, + require_proposal, + store_lock, + store_proposals, + validate_decision, + validate_human_confirmation, + validate_safe_object, +) + +_REVIEW_CARD_DELIVERY_FIELDS = frozenset( + { + "provider", + "message_id", + "chat_id", + "app_id", + "cli_bin", + "sender_profile", + "binding_digest", + "card_digest", + "submitted_card", + "delivered_at", + "authorized_principal", + } +) +_REVIEW_CARD_CONFIRMATION_FIELDS = frozenset( + { + "provider", + "event_id", + "principal", + "message_id", + "chat_id", + "app_id", + "audience_id", + "state_fingerprint", + "card_digest", + "confirmed_at", + "actor_class", + "verification_kind", + } +) +_REVIEW_CARD_RESULT_FIELDS = frozenset({"card_digest", "transport", "delivered_at"}) + + +def record_review_card_delivery( + store: ActionStoreBackend, + proposal_id: str, + *, + audience_id: str, + delivery: Mapping[str, object], +) -> JsonDict: + """Bind one verified external review surface to a typed proposal. + + A proposal may be rendered into more than one audience, but every card + retains the proposal id and state fingerprint owned by the typed action + store. Recording all audiences on that one proposal is what prevents a + manager card and a Goal card from becoming two independent approvals. + """ + audience = _opaque_id(audience_id, field="review_card.audience_id") + safe_delivery = validate_safe_object( + delivery, + path=f"review_card.deliveries.{audience}", + label="review card delivery", + required_keys=_REVIEW_CARD_DELIVERY_FIELDS, + bounded_fields=_REVIEW_CARD_DELIVERY_FIELDS - {"submitted_card"}, + field_prefix="review_card.delivery", + ) + submitted_card = safe_delivery.get("submitted_card") + if not is_str_dict(submitted_card): + raise ValueError("review card submitted payload must be an object") + if _canonical_digest(submitted_card) != safe_delivery["card_digest"]: + raise ActionConflictError("review card submitted payload drifted") + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="record_review_card_delivery"): + payload = store._read() + proposal = require_proposal(payload, token) + if proposal.get("action_kind") != "team.plan": + raise ActionConflictError("only a team plan can bind this review card") + review_card = proposal.get("review_card") + if review_card is None: + raise ActionConflictError( + "review card audiences must be prepared before delivery" + ) + if not is_str_dict(review_card): + raise ValueError("typed review card state is malformed") + if review_card.get("state_fingerprint") != proposal.get( + "expected_state_fingerprint" + ): + raise ActionConflictError("review card state fingerprint drifted") + if review_card.get("authorized_principal") != safe_delivery.get( + "authorized_principal" + ): + raise ActionConflictError( + "review card audience changed the authorized principal" + ) + deliveries = review_card.get("deliveries") + if not is_str_dict(deliveries): + raise ValueError("typed review card deliveries are malformed") + expected_audiences = review_card.get("expected_audience_ids") + if ( + not isinstance(expected_audiences, list) + or audience not in expected_audiences + ): + raise ActionConflictError("review card audience was not prepared") + existing = deliveries.get(audience) + if existing is not None: + immutable_fields = _REVIEW_CARD_DELIVERY_FIELDS - {"delivered_at"} + if not isinstance(existing, Mapping) or any( + existing.get(field) != safe_delivery.get(field) + for field in immutable_fields + ): + raise ActionConflictError( + "review card audience is already bound to another message" + ) + return proposal + if review_card.get("confirmation") is not None: + raise ActionConflictError("review card decision is already consumed") + deliveries[audience] = safe_delivery + return commit_proposal_mutation(store, payload, proposal) + + +def prepare_review_card_delivery( + store: ActionStoreBackend, + proposal_id: str, + *, + audience_ids: Sequence[str], + authorized_principal: str, +) -> JsonDict: + """Freeze every audience before the first actionable card is sent.""" + normalized_audiences = sorted( + {_opaque_id(value, field="review_card.audience_id") for value in audience_ids} + ) + if not normalized_audiences or len(normalized_audiences) != len(audience_ids): + raise ValueError("review card audiences must be non-empty and unique") + principal = _opaque_id( + authorized_principal, field="review_card.authorized_principal" + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="prepare_review_card_delivery"): + payload = store._read() + proposal = require_proposal(payload, token) + if proposal.get("action_kind") != "team.plan": + raise ActionConflictError("only a team plan can bind this review card") + expected: JsonDict = { + "schema_version": "loopx_review_card_delivery_v0", + "state_fingerprint": proposal.get("expected_state_fingerprint"), + "expected_audience_ids": normalized_audiences, + "deliveries": {}, + "confirmation": None, + "authorized_principal": principal, + } + existing = proposal.get("review_card") + if existing is None: + proposal["review_card"] = expected + return commit_proposal_mutation(store, payload, proposal) + if not is_str_dict(existing): + raise ValueError("typed review card state is malformed") + immutable = { + "schema_version": expected["schema_version"], + "state_fingerprint": expected["state_fingerprint"], + "expected_audience_ids": expected["expected_audience_ids"], + "authorized_principal": expected["authorized_principal"], + } + if any(existing.get(key) != value for key, value in immutable.items()): + raise ActionConflictError("review card audience plan drifted") + return proposal + + +def decide_review_card( + store: ActionStoreBackend, + proposal_id: str, + *, + decision: str, + confirmation: Mapping[str, object], +) -> JsonDict: + """Consume one verified card decision across every delivered audience.""" + selected_decision = validate_decision(decision, label="review card") + safe_confirmation = validate_human_confirmation( + confirmation, + path="review_card.confirmation", + label="review card confirmation", + required_keys=_REVIEW_CARD_CONFIRMATION_FIELDS, + ) + token = _opaque_id(proposal_id, field="proposal_id") + audience = _opaque_id( + safe_confirmation["audience_id"], field="review_card.audience_id" + ) + with store_lock(store.path, operation="decide_review_card"): + payload = store._read() + proposal = store_proposals(payload).get(token) + review_card = ( + proposal.get("review_card") if is_str_dict(proposal) else None + ) + if not is_str_dict(proposal) or not is_str_dict(review_card): + raise KeyError("typed review card was not found") + deliveries = review_card.get("deliveries") + delivery = deliveries.get(audience) if is_str_dict(deliveries) else None + if not is_str_dict(deliveries) or not is_str_dict(delivery): + raise ActionConflictError("review card audience was not delivered") + expected_audiences = review_card.get("expected_audience_ids") + if ( + not isinstance(expected_audiences, list) + or set(deliveries) != set(expected_audiences) + ): + raise ActionConflictError( + "review card audiences are not completely delivered" + ) + expected = { + "provider": delivery.get("provider"), + "message_id": delivery.get("message_id"), + "chat_id": delivery.get("chat_id"), + "app_id": delivery.get("app_id"), + "state_fingerprint": review_card.get("state_fingerprint"), + "card_digest": delivery.get("card_digest"), + } + if any( + safe_confirmation.get(field) != value for field, value in expected.items() + ): + raise ActionConflictError( + "review card callback does not match the delivered request" + ) + if safe_confirmation.get("principal") != review_card.get( + "authorized_principal" + ): + raise ActionConflictError( + "principal is not authorized for this review card" + ) + existing = review_card.get("confirmation") + if is_str_dict(existing): + # Every audience is a view of the same proposal. Once one exact + # decision wins, later clicks only observe that decision and can + # never launch a second canonical effect. + return proposal + status = str(proposal.get("status") or "") + if status not in {"preview_ready", "deferred"}: + raise ActionConflictError( + "review card proposal is no longer awaiting confirmation" + ) + now = current_utc_now() + review_card["confirmation"] = { + **safe_confirmation, + "decision": selected_decision, + } + if selected_decision == "confirm": + proposal["status"] = "applying" + proposal["gate"] = None + proposal["failure"] = None + else: + proposal["status"] = "rejected" + proposal["rejected_at"] = now + return commit_proposal_mutation(store, payload, proposal, updated_at=now) + + +def record_review_card_result_delivery( + store: ActionStoreBackend, + proposal_id: str, + *, + audience_id: str, + result: Mapping[str, object], +) -> JsonDict: + """Record exact result-card readback for one already-bound audience.""" + audience = _opaque_id(audience_id, field="review_card.audience_id") + safe_result = validate_safe_object( + result, + path=f"review_card.deliveries.{audience}.result", + label="review card result delivery", + required_keys=_REVIEW_CARD_RESULT_FIELDS, + bounded_fields=_REVIEW_CARD_RESULT_FIELDS, + field_prefix="review_card.result", + ) + token = _opaque_id(proposal_id, field="proposal_id") + with store_lock(store.path, operation="record_review_card_result_delivery"): + payload = store._read() + proposal = store_proposals(payload).get(token) + review_card = ( + proposal.get("review_card") if is_str_dict(proposal) else None + ) + deliveries = ( + review_card.get("deliveries") if is_str_dict(review_card) else None + ) + delivery = deliveries.get(audience) if is_str_dict(deliveries) else None + if not is_str_dict(proposal) or not is_str_dict(delivery): + raise KeyError("typed review card audience was not found") + existing = delivery.get("result") + if existing is not None: + if existing != safe_result: + raise ActionConflictError( + "review card result delivery is already immutable" + ) + return proposal + delivery["result"] = safe_result + return commit_proposal_mutation(store, payload, proposal) diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py index 1e0a8e0940..7a8121eb3c 100644 --- a/loopx/chat/session_open.py +++ b/loopx/chat/session_open.py @@ -122,7 +122,10 @@ def read_goal_creation_session( recorded_proposal = action_store.load(proposal_id) if recorded_proposal is None: raise ValueError("The original creation checkpoint is unavailable") - recorded = ((recorded_proposal.get("checkpoint") or {}).get("steps") or {}).get("first_session_opened") or {} + checkpoint = recorded_proposal.get("checkpoint") + steps = checkpoint.get("steps") if isinstance(checkpoint, Mapping) else None + raw_recorded = steps.get("first_session_opened") if isinstance(steps, Mapping) else None + recorded = raw_recorded if isinstance(raw_recorded, Mapping) else {} for field in ("channel_id", "managed_agent_id", "goal_instance_id"): if field in recorded and recorded[field] != session.get(field): raise ValueError("The original first Session route changed; restore its recorded identity") diff --git a/loopx/chat_action_store.py b/loopx/chat_action_store.py index 8ed4bd2311..0305686bc5 100644 --- a/loopx/chat_action_store.py +++ b/loopx/chat_action_store.py @@ -2,27 +2,44 @@ from __future__ import annotations -from collections.abc import Callable -from datetime import datetime, timedelta, timezone -import hashlib +from collections.abc import Callable, Mapping, Sequence import json -import math import os from pathlib import Path -import re -from typing import Any, Mapping, Sequence import uuid +from .chat import action_store_common as _common +from .chat import action_store_operations as _operations +from .chat import action_store_review_cards as _review_cards +from .chat.action_store_common import ( + AUTHENTICATED_LARK_CARD_CALLBACK, + CHAT_ACTION_PROPOSAL_SCHEMA_VERSION, + CHAT_ACTION_STORE_SCHEMA_VERSION, + HUMAN_ACTOR_CLASS, + OPERATION_ENVELOPE_SCHEMA_VERSION, + OPERATION_LIFECYCLE_STATES, + PROPOSAL_STATES, + RETRYABLE_PROPOSAL_STATES, + ActionConflictError, + JsonDict, + JsonPrimitive, + JsonValue, + ObjectDict, + _bounded_text, + _canonical_digest, + _opaque_id, + _safe_json_value, + _utc_now, + is_str_dict, + normalize_idempotency_key, + safe_object_dict, + store_idempotency, + store_proposals, +) from .file_lock import exclusive_file_lock from .public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID from .registry import atomic_write_json - -CHAT_ACTION_STORE_SCHEMA_VERSION = "loopx_chat_action_store_v1" -CHAT_ACTION_PROPOSAL_SCHEMA_VERSION = "loopx_chat_action_proposal_v1" -HUMAN_ACTOR_CLASS = "human" -AUTHENTICATED_LARK_CARD_CALLBACK = "lark_authenticated_card_callback_v1" - ACTION_KINDS = { "goal.acceptance.check", "goal.create", @@ -40,122 +57,33 @@ "pr.merge", "team.plan", } -PROPOSAL_STATES = { - "preview_ready", - "applying", - "gated", - "failed", - "rejected", - "deferred", - "cancelled", - "stale", - "applied", -} -RETRYABLE_PROPOSAL_STATES = {"preview_ready", "gated", "failed", "deferred"} - -OPERATION_ENVELOPE_SCHEMA_VERSION = "loopx_operation_envelope_v0" -OPERATION_LIFECYCLE_STATES = { - "awaiting_confirmation", - "claimed", - "outcome_observed", -} - -_LOCAL_PATH = re.compile( - r"(?:^|[\s\"'])(?:/Users/|/home/|/private/|/var/folders/|/tmp/|~[/\\]|file://)", - re.IGNORECASE, -) -_SENSITIVE_TEXT = re.compile( - r"(?:bearer\s+[A-Za-z0-9._~+/-]+|sk-[A-Za-z0-9_-]{4,}|raw\s+(?:provider|tool)\s+(?:payload|output))", - re.IGNORECASE, -) -_SENSITIVE_KEYS = { - "api_key", - "apikey", - "authorization", - "auth_token", - "access_token", - "refresh_token", - "password", - "passwd", - "secret", - "credentials", - "credential", - "private_key", - "raw_provider_payload", - "provider_payload", - "raw_tool_output", - "tool_output", - "stderr", - "command", -} - - -class ActionConflictError(RuntimeError): - """Raised when a typed action transition conflicts with durable state.""" - - -def _utc_now() -> str: - return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") - - -def _opaque_id(value: Any, *, field: str) -> str: - token = str(value or "").strip() - if not _OPAQUE_ID.fullmatch(token): - raise ValueError(f"{field} must be a compact opaque id") - return token - -def normalize_idempotency_key(value: Any) -> str: - """Return the canonical token this store binds and persists.""" - return _opaque_id(value, field="idempotency_key") - - -def _bounded_text(value: Any, *, field: str, limit: int = 4000) -> str: - text = str(value or "").strip() - if not text or len(text) > limit or any(ord(character) < 32 for character in text): - raise ValueError(f"{field} must be bounded visible text") - return text - - -def _safe_json_value(value: Any, *, path: str = "payload") -> Any: - if value is None or isinstance(value, (bool, int)): - return value - if isinstance(value, float): - if not math.isfinite(value): - raise ValueError(f"{path} must contain finite JSON numbers") - return value - if isinstance(value, str): - if _LOCAL_PATH.search(value) or _SENSITIVE_TEXT.search(value): - raise ValueError(f"{path} contains sensitive material") - if len(value) > 8000 or any(ord(character) < 9 for character in value): - raise ValueError(f"{path} must contain bounded public-safe text") - return value - if isinstance(value, Mapping): - safe: dict[str, Any] = {} - for raw_key, item in value.items(): - key = str(raw_key).strip() - normalized_key = re.sub(r"[^a-z0-9]+", "_", key.lower()).strip("_") - if not key or normalized_key in _SENSITIVE_KEYS: - raise ValueError(f"{path}.{key or ''} is a sensitive field") - safe[key] = _safe_json_value(item, path=f"{path}.{key}") - return safe - if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray)): - return [ - _safe_json_value(item, path=f"{path}[{index}]") - for index, item in enumerate(value) - ] - raise ValueError(f"{path} must be JSON-compatible") - - -def _canonical_digest(payload: Mapping[str, Any]) -> str: - encoded = json.dumps( - payload, - allow_nan=False, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - ).encode("utf-8") - return hashlib.sha256(encoded).hexdigest() +__all__ = [ + "ACTION_KINDS", + "AUTHENTICATED_LARK_CARD_CALLBACK", + "ActionConflictError", + "CHAT_ACTION_PROPOSAL_SCHEMA_VERSION", + "CHAT_ACTION_STORE_SCHEMA_VERSION", + "ChatActionStore", + "HUMAN_ACTOR_CLASS", + "JsonDict", + "JsonPrimitive", + "JsonValue", + "OPERATION_ENVELOPE_SCHEMA_VERSION", + "OPERATION_LIFECYCLE_STATES", + "ObjectDict", + "PROPOSAL_STATES", + "RETRYABLE_PROPOSAL_STATES", + "_OPAQUE_ID", + "_bounded_text", + "_canonical_digest", + "_opaque_id", + "_safe_json_value", + "_utc_now", + "atomic_write_json", + "exclusive_file_lock", + "normalize_idempotency_key", +] class ChatActionStore: @@ -168,37 +96,39 @@ def __init__(self, root: Path) -> None: os.chmod(self.root, 0o700) if not self.path.exists(): with exclusive_file_lock( - self.path, agent_id="loopx-chat", operation="initialize_chat_action_store" + self.path, + agent_id="loopx-chat", + operation="initialize_chat_action_store", ): if not self.path.exists(): atomic_write_json(self.path, self._empty_payload()) os.chmod(self.path, 0o600) @staticmethod - def _empty_payload() -> dict[str, Any]: + def _empty_payload() -> JsonDict: return { "schema_version": CHAT_ACTION_STORE_SCHEMA_VERSION, "proposals": {}, "idempotency": {}, } - def _read(self) -> dict[str, Any]: + def _read(self) -> JsonDict: try: - payload = json.loads(self.path.read_text(encoding="utf-8")) + payload: object = json.loads(self.path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise ValueError("typed Chat action store is unreadable") from exc if ( - not isinstance(payload, dict) + not is_str_dict(payload) or payload.get("schema_version") != CHAT_ACTION_STORE_SCHEMA_VERSION ): raise ValueError("typed Chat action store has an unsupported schema") - if not isinstance(payload.get("proposals"), dict) or not isinstance( - payload.get("idempotency"), dict + if not is_str_dict(payload.get("proposals")) or not is_str_dict( + payload.get("idempotency") ): raise ValueError("typed Chat action store is malformed") return payload - def _write(self, payload: dict[str, Any]) -> None: + def _write(self, payload: JsonDict) -> None: atomic_write_json(self.path, payload, preserve_mode=True) os.chmod(self.path, 0o600) @@ -207,43 +137,41 @@ def create_preview( *, action_kind: str, summary: str, - normalized_parameters: Mapping[str, Any], - context: Mapping[str, Any], + normalized_parameters: Mapping[str, object], + context: Mapping[str, object], expected_state_fingerprint: str, permission_classification: str, - validation_evidence: Sequence[Any], - available_transitions: Sequence[Any], + validation_evidence: Sequence[object], + available_transitions: Sequence[object], idempotency_key: str, - canonical_update_basis: Mapping[str, Any] | None = None, - workspace_binding: Mapping[str, Any] | None = None, - ) -> dict[str, Any]: + canonical_update_basis: Mapping[str, object] | None = None, + workspace_binding: Mapping[str, object] | None = None, + ) -> JsonDict: selected_kind = str(action_kind or "").strip() if selected_kind not in ACTION_KINDS: raise ValueError(f"unsupported action_kind: {selected_kind or ''}") - request = _safe_json_value( - { - "action_kind": selected_kind, - "summary": _bounded_text(summary, field="summary"), - "normalized_parameters": dict(normalized_parameters), - "context": dict(context), - "expected_state_fingerprint": _bounded_text( - expected_state_fingerprint, - field="expected_state_fingerprint", - limit=512, - ), - "permission_classification": _opaque_id( - permission_classification, - field="permission_classification", - ), - "validation_evidence": list(validation_evidence), - "available_transitions": list(available_transitions), - **({"canonical_update_basis": dict(canonical_update_basis)} - if canonical_update_basis is not None else {}), - **({"workspace_binding": dict(workspace_binding)} - if workspace_binding is not None else {}), - }, - path="preview", - ) + request_input: JsonDict = { + "action_kind": selected_kind, + "summary": _bounded_text(summary, field="summary"), + "normalized_parameters": dict(normalized_parameters), + "context": dict(context), + "expected_state_fingerprint": _bounded_text( + expected_state_fingerprint, + field="expected_state_fingerprint", + limit=512, + ), + "permission_classification": _opaque_id( + permission_classification, + field="permission_classification", + ), + "validation_evidence": list(validation_evidence), + "available_transitions": list(available_transitions), + } + if canonical_update_basis is not None: + request_input["canonical_update_basis"] = dict(canonical_update_basis) + if workspace_binding is not None: + request_input["workspace_binding"] = dict(workspace_binding) + request = safe_object_dict(request_input, path="preview", label="preview") key = normalize_idempotency_key(idempotency_key) request_digest = _canonical_digest(request) with exclusive_file_lock( @@ -252,15 +180,17 @@ def create_preview( operation="create_chat_action_preview", ): payload = self._read() - existing_binding = payload["idempotency"].get(key) - if isinstance(existing_binding, dict): + proposals = store_proposals(payload) + idempotency = store_idempotency(payload) + existing_binding = idempotency.get(key) + if is_str_dict(existing_binding): proposal_id = str(existing_binding.get("proposal_id") or "") if existing_binding.get("request_digest") != request_digest: raise ActionConflictError( "idempotency key already belongs to another preview" ) - existing = payload["proposals"].get(proposal_id) - if not isinstance(existing, dict): + existing = proposals.get(proposal_id) + if not is_str_dict(existing): raise ValueError( "typed Chat action idempotency index is inconsistent" ) @@ -268,7 +198,7 @@ def create_preview( now = _utc_now() proposal_id = f"proposal-{uuid.uuid4().hex}" - proposal = { + proposal: JsonDict = { "schema_version": CHAT_ACTION_PROPOSAL_SCHEMA_VERSION, "proposal_id": proposal_id, **request, @@ -290,8 +220,8 @@ def create_preview( "deferred_at": None, "applied_at": None, } - payload["proposals"][proposal_id] = proposal - payload["idempotency"][key] = { + proposals[proposal_id] = proposal + idempotency[key] = { "proposal_id": proposal_id, "request_digest": request_digest, } @@ -302,189 +232,40 @@ def replay_or_reuse_preview( self, *, action_kind: str, - context: Mapping[str, Any], - normalized_parameters: Mapping[str, Any], + context: Mapping[str, object], + normalized_parameters: Mapping[str, object], idempotency_key: str, shared_fields: tuple[str, ...], reusable_states: set[str], matches_review_basis: Callable[[object], bool] | None = None, require_exact_context: bool = False, summary: str | None = None, - ) -> dict[str, Any] | None: + ) -> JsonDict | None: """Resolve an accepted request or bind it to an equivalent pending review.""" - if summary is not None: - _safe_json_value(_bounded_text(summary, field="summary"), path="preview.summary") - key = normalize_idempotency_key(idempotency_key) - request = _safe_json_value({ - "action_kind": action_kind, - "context": context, - "normalized_parameters": normalized_parameters, - }) - digest = _canonical_digest(request) - - def matches_scope(row: dict[str, Any]) -> bool: - row_context = row.get("context") - return ( - row.get("action_kind") == action_kind and isinstance(row_context, dict) - and all(row_context.get(field) == value for field, value in context.items()) - ) - - with exclusive_file_lock( - self.path, agent_id="loopx-chat", operation="reuse_chat_action_preview" - ): - payload = self._read() - proposals = payload["proposals"] - bindings = payload["idempotency"] - if key in bindings: - binding = bindings[key] - row = proposals.get(binding["proposal_id"]) - if not isinstance(row, dict): - raise ValueError("typed Chat action idempotency index is inconsistent") - # Original previews already carry their full normalized request. - # Reused previews keep the later request's identity in the index. - previous_digest = binding.get("reused_request_digest") - if previous_digest is not None: - same_request = previous_digest == digest - else: - same_request = row["normalized_parameters"] == request["normalized_parameters"] and ( - not require_exact_context or row.get("context") == request["context"] - ) - if not matches_scope(row) or not same_request: - raise ActionConflictError("idempotency key already belongs to another preview") - return row - - if not reusable_states or matches_review_basis is None: - return None - pending = max( - ( - row for row in proposals.values() - if isinstance(row, dict) and row.get("status") in reusable_states - and matches_scope(row) - and isinstance(row.get("normalized_parameters"), dict) - and all( - row["normalized_parameters"].get(field) == normalized_parameters[field] - for field in shared_fields - ) - and matches_review_basis(row.get("expected_state_fingerprint")) - ), - key=lambda row: (row.get("updated_at") or "", row["proposal_id"]), - default=None, - ) - if pending is None: - return None - bindings[key] = { - "proposal_id": pending["proposal_id"], - "reused_request_digest": digest, - } - self._write(payload) - return pending + return _common.replay_or_reuse_preview( + self, + action_kind=action_kind, + context=context, + normalized_parameters=normalized_parameters, + idempotency_key=idempotency_key, + shared_fields=shared_fields, + reusable_states=reusable_states, + matches_review_basis=matches_review_basis, + require_exact_context=require_exact_context, + summary=summary, + ) def record_review_card_delivery( self, proposal_id: str, *, audience_id: str, - delivery: Mapping[str, Any], - ) -> dict[str, Any]: - """Bind one verified external review surface to a typed proposal. - - A proposal may be rendered into more than one audience, but every card - retains the proposal id and state fingerprint owned by the typed action - store. Recording all audiences on that one proposal is what prevents a - manager card and a Goal card from becoming two independent approvals. - """ - - audience = _opaque_id(audience_id, field="review_card.audience_id") - safe_delivery = _safe_json_value( - dict(delivery), path=f"review_card.deliveries.{audience}" + delivery: Mapping[str, object], + ) -> JsonDict: + """Bind one verified external review surface to a typed proposal.""" + return _review_cards.record_review_card_delivery( + self, proposal_id, audience_id=audience_id, delivery=delivery ) - if not isinstance(safe_delivery, dict): - raise ValueError("review card delivery must be an object") - required = { - "provider", - "message_id", - "chat_id", - "app_id", - "cli_bin", - "sender_profile", - "binding_digest", - "card_digest", - "submitted_card", - "delivered_at", - "authorized_principal", - } - if set(safe_delivery) != required: - raise ValueError( - "review card delivery has unsupported or missing fields" - ) - for field in required - {"submitted_card"}: - _bounded_text( - safe_delivery.get(field), - field=f"review_card.delivery.{field}", - limit=512, - ) - submitted_card = safe_delivery.get("submitted_card") - if not isinstance(submitted_card, dict): - raise ValueError("review card submitted payload must be an object") - if _canonical_digest(submitted_card) != safe_delivery["card_digest"]: - raise ActionConflictError("review card submitted payload drifted") - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="record_review_card_delivery", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - if proposal.get("action_kind") != "team.plan": - raise ActionConflictError( - "only a team plan can bind this review card" - ) - review_card = proposal.get("review_card") - if review_card is None: - raise ActionConflictError( - "review card audiences must be prepared before delivery" - ) - if not isinstance(review_card, dict): - raise ValueError("typed review card state is malformed") - if review_card.get("state_fingerprint") != proposal.get( - "expected_state_fingerprint" - ): - raise ActionConflictError("review card state fingerprint drifted") - if review_card.get("authorized_principal") != safe_delivery.get( - "authorized_principal" - ): - raise ActionConflictError( - "review card audience changed the authorized principal" - ) - deliveries = review_card.get("deliveries") - if not isinstance(deliveries, dict): - raise ValueError("typed review card deliveries are malformed") - expected_audiences = review_card.get("expected_audience_ids") - if ( - not isinstance(expected_audiences, list) - or audience not in expected_audiences - ): - raise ActionConflictError("review card audience was not prepared") - existing = deliveries.get(audience) - if existing is not None: - immutable_fields = required - {"delivered_at"} - if not isinstance(existing, Mapping) or any( - existing.get(field) != safe_delivery.get(field) - for field in immutable_fields - ): - raise ActionConflictError( - "review card audience is already bound to another message" - ) - return proposal - if review_card.get("confirmation") is not None: - raise ActionConflictError("review card decision is already consumed") - deliveries[audience] = safe_delivery - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal def prepare_review_card_delivery( self, @@ -492,874 +273,153 @@ def prepare_review_card_delivery( *, audience_ids: Sequence[str], authorized_principal: str, - ) -> dict[str, Any]: + ) -> JsonDict: """Freeze every audience before the first actionable card is sent.""" - - normalized_audiences = sorted( - {_opaque_id(value, field="review_card.audience_id") for value in audience_ids} - ) - if not normalized_audiences or len(normalized_audiences) != len(audience_ids): - raise ValueError("review card audiences must be non-empty and unique") - principal = _opaque_id( - authorized_principal, field="review_card.authorized_principal" + return _review_cards.prepare_review_card_delivery( + self, + proposal_id, + audience_ids=audience_ids, + authorized_principal=authorized_principal, ) - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="prepare_review_card_delivery", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - if proposal.get("action_kind") != "team.plan": - raise ActionConflictError( - "only a team plan can bind this review card" - ) - expected = { - "schema_version": "loopx_review_card_delivery_v0", - "state_fingerprint": proposal.get("expected_state_fingerprint"), - "expected_audience_ids": normalized_audiences, - "deliveries": {}, - "confirmation": None, - "authorized_principal": principal, - } - existing = proposal.get("review_card") - if existing is None: - proposal["review_card"] = expected - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal - if not isinstance(existing, dict): - raise ValueError("typed review card state is malformed") - immutable = { - "schema_version": expected["schema_version"], - "state_fingerprint": expected["state_fingerprint"], - "expected_audience_ids": expected["expected_audience_ids"], - "authorized_principal": expected["authorized_principal"], - } - if any(existing.get(key) != value for key, value in immutable.items()): - raise ActionConflictError("review card audience plan drifted") - return proposal def decide_review_card( self, proposal_id: str, *, decision: str, - confirmation: Mapping[str, Any], - ) -> dict[str, Any]: + confirmation: Mapping[str, object], + ) -> JsonDict: """Consume one verified card decision across every delivered audience.""" - - selected_decision = str(decision or "").strip().lower() - if selected_decision not in {"confirm", "reject"}: - raise ValueError("review card decision must be confirm or reject") - safe_confirmation = _safe_json_value( - dict(confirmation), path="review_card.confirmation" - ) - if not isinstance(safe_confirmation, dict): - raise ValueError("review card confirmation must be an object") - required = { - "provider", - "event_id", - "principal", - "message_id", - "chat_id", - "app_id", - "audience_id", - "state_fingerprint", - "card_digest", - "confirmed_at", - "actor_class", - "verification_kind", - } - if set(safe_confirmation) != required: - raise ValueError( - "review card confirmation has unsupported or missing fields" - ) - for field in required: - _bounded_text( - safe_confirmation.get(field), - field=f"review_card.confirmation.{field}", - limit=512, - ) - if safe_confirmation["actor_class"] != HUMAN_ACTOR_CLASS: - raise ValueError("review card confirmation requires a human actor") - _opaque_id( - safe_confirmation["verification_kind"], - field="review_card.confirmation.verification_kind", - ) - token = _opaque_id(proposal_id, field="proposal_id") - audience = _opaque_id( - safe_confirmation["audience_id"], field="review_card.audience_id" + return _review_cards.decide_review_card( + self, proposal_id, decision=decision, confirmation=confirmation ) - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="decide_review_card", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - review_card = ( - proposal.get("review_card") if isinstance(proposal, dict) else None - ) - if not isinstance(review_card, dict): - raise KeyError("typed review card was not found") - deliveries = review_card.get("deliveries") - delivery = ( - deliveries.get(audience) if isinstance(deliveries, dict) else None - ) - if not isinstance(delivery, dict): - raise ActionConflictError("review card audience was not delivered") - expected_audiences = review_card.get("expected_audience_ids") - if ( - not isinstance(expected_audiences, list) - or set(deliveries) != set(expected_audiences) - ): - raise ActionConflictError( - "review card audiences are not completely delivered" - ) - expected = { - "provider": delivery.get("provider"), - "message_id": delivery.get("message_id"), - "chat_id": delivery.get("chat_id"), - "app_id": delivery.get("app_id"), - "state_fingerprint": review_card.get("state_fingerprint"), - "card_digest": delivery.get("card_digest"), - } - if any( - safe_confirmation.get(field) != value - for field, value in expected.items() - ): - raise ActionConflictError( - "review card callback does not match the delivered request" - ) - if safe_confirmation.get("principal") != review_card.get( - "authorized_principal" - ): - raise ActionConflictError( - "principal is not authorized for this review card" - ) - existing = review_card.get("confirmation") - if isinstance(existing, dict): - # Every audience is a view of the same proposal. Once one exact - # decision wins, later clicks only observe that decision and can - # never launch a second canonical effect. - return proposal - status = str(proposal.get("status") or "") - if status not in {"preview_ready", "deferred"}: - raise ActionConflictError( - "review card proposal is no longer awaiting confirmation" - ) - now = _utc_now() - review_card["confirmation"] = { - **safe_confirmation, - "decision": selected_decision, - } - if selected_decision == "confirm": - proposal["status"] = "applying" - proposal["gate"] = None - proposal["failure"] = None - else: - proposal["status"] = "rejected" - proposal["rejected_at"] = now - proposal["updated_at"] = now - self._write(payload) - return proposal def record_review_card_result_delivery( self, proposal_id: str, *, audience_id: str, - result: Mapping[str, Any], - ) -> dict[str, Any]: + result: Mapping[str, object], + ) -> JsonDict: """Record exact result-card readback for one already-bound audience.""" - - audience = _opaque_id(audience_id, field="review_card.audience_id") - safe_result = _safe_json_value( - dict(result), path=f"review_card.deliveries.{audience}.result" + return _review_cards.record_review_card_result_delivery( + self, proposal_id, audience_id=audience_id, result=result ) - if not isinstance(safe_result, dict): - raise ValueError("review card result delivery must be an object") - required = {"card_digest", "transport", "delivered_at"} - if set(safe_result) != required: - raise ValueError( - "review card result delivery has unsupported or missing fields" - ) - for field in required: - _bounded_text( - safe_result.get(field), - field=f"review_card.result.{field}", - limit=512, - ) - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="record_review_card_result_delivery", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - review_card = ( - proposal.get("review_card") if isinstance(proposal, dict) else None - ) - deliveries = ( - review_card.get("deliveries") - if isinstance(review_card, dict) - else None - ) - delivery = ( - deliveries.get(audience) if isinstance(deliveries, dict) else None - ) - if not isinstance(delivery, dict): - raise KeyError("typed review card audience was not found") - existing = delivery.get("result") - if existing is not None: - if existing != safe_result: - raise ActionConflictError( - "review card result delivery is already immutable" - ) - return proposal - delivery["result"] = safe_result - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal - - def arm_operation(self, proposal_id: str) -> dict[str, Any]: - """Turn one provider-neutral preview into the canonical confirmation gate. - The immutable request already lives on the proposal. This method adds - only lifecycle state derived from that request; Lark, the Dashboard and - domain executors must all read this same envelope. - """ - - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="arm_operation_confirmation", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - if proposal.get("action_kind") != "operation.execute": - raise ActionConflictError( - "only operation.execute previews can be armed" - ) - existing = proposal.get("operation") - if isinstance(existing, dict): - if ( - existing.get("schema_version") != OPERATION_ENVELOPE_SCHEMA_VERSION - or existing.get("lifecycle_state") not in OPERATION_LIFECYCLE_STATES - ): - raise ValueError("typed operation envelope is malformed") - return proposal - if proposal.get("status") != "preview_ready": - raise ActionConflictError( - f"proposal in {proposal.get('status')} state cannot await confirmation" - ) - parameters = proposal.get("normalized_parameters") - if not isinstance(parameters, dict): - raise ValueError("typed operation parameters are malformed") - now = _utc_now() - confirmation_digest = _canonical_digest( - { - "action_kind": "operation.execute", - "normalized_parameters": parameters, - "request_digest": proposal.get("request_digest"), - } - ) - operation = { - "schema_version": OPERATION_ENVELOPE_SCHEMA_VERSION, - "operation_id": token, - "lifecycle_state": "awaiting_confirmation", - "confirmation_digest": confirmation_digest, - "payload_digest": parameters.get("payload_digest"), - "projection_digest": parameters.get("projection_digest"), - "executor_revision": ( - parameters.get("executor", {}).get("revision") - if isinstance(parameters.get("executor"), dict) - else None - ), - "destination_account_ref": parameters.get("destination_account_ref"), - "expires_at": parameters.get("expires_at"), - "authorized_principals": list( - parameters.get("authorized_principals") or [] - ), - "delivery": None, - "confirmation": None, - "claim": None, - "outcome": None, - "result_delivery": None, - "armed_at": now, - } - proposal["operation"] = _safe_json_value(operation, path="operation") - proposal["status"] = "gated" - proposal["gate"] = { - "kind": "human_operation_confirmation", - "summary": "This exact operation is awaiting an authenticated human decision.", - "next_action": "Use the bound operation card; ordinary typed-action apply is not confirmation.", - } - proposal["updated_at"] = now - self._write(payload) - return proposal + def arm_operation(self, proposal_id: str) -> JsonDict: + """Turn one provider-neutral preview into the canonical confirmation gate.""" + return _operations.arm_operation(self, proposal_id) def record_operation_delivery( - self, - proposal_id: str, - *, - delivery: Mapping[str, Any], - ) -> dict[str, Any]: + self, proposal_id: str, *, delivery: Mapping[str, object] + ) -> JsonDict: """Bind the exact provider message which may attest a later click.""" - - safe_delivery = _safe_json_value(dict(delivery), path="operation.delivery") - if not isinstance(safe_delivery, dict): - raise ValueError("operation delivery must be an object") - for field in ( - "provider", - "message_id", - "chat_id", - "app_id", - "binding_digest", - "card_digest", - "delivered_at", - ): - _bounded_text( - safe_delivery.get(field), - field=f"operation.delivery.{field}", - limit=512, - ) - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="record_operation_delivery", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - operation = ( - proposal.get("operation") if isinstance(proposal, dict) else None - ) - if not isinstance(operation, dict): - raise KeyError("typed operation was not found") - if operation.get("lifecycle_state") != "awaiting_confirmation": - existing = operation.get("delivery") - if isinstance(existing, dict) and existing == safe_delivery: - return proposal - raise ActionConflictError("operation is no longer awaiting delivery") - existing = operation.get("delivery") - if existing is not None: - if existing != safe_delivery: - raise ActionConflictError( - "operation is already bound to another provider message" - ) - return proposal - operation["delivery"] = safe_delivery - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal + return _operations.record_operation_delivery( + self, proposal_id, delivery=delivery + ) def record_operation_delivery_snapshot( - self, - proposal_id: str, - *, - submitted_card: Mapping[str, Any], - ) -> dict[str, Any]: + self, proposal_id: str, *, submitted_card: Mapping[str, object] + ) -> JsonDict: """Persist the immutable sent card after verifying its recorded digest.""" - - safe_card = _safe_json_value( - dict(submitted_card), path="operation.delivery.submitted_card" + return _operations.record_operation_delivery_snapshot( + self, proposal_id, submitted_card=submitted_card ) - if not isinstance(safe_card, dict): - raise ValueError("operation submitted card must be an object") - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="record_operation_delivery_snapshot", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - operation = ( - proposal.get("operation") if isinstance(proposal, dict) else None - ) - delivery = ( - operation.get("delivery") if isinstance(operation, dict) else None - ) - if not isinstance(delivery, dict): - raise ActionConflictError("operation card delivery was not recorded") - if _canonical_digest(safe_card) != delivery.get("card_digest"): - raise ActionConflictError("operation submitted card digest drifted") - existing = delivery.get("submitted_card") - if existing is not None: - if existing != safe_card: - raise ActionConflictError( - "operation submitted card snapshot already differs" - ) - return proposal - delivery["submitted_card"] = safe_card - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal def decide_operation( self, proposal_id: str, *, decision: str, - confirmation: Mapping[str, Any], - ) -> dict[str, Any]: - """Atomically reject, or confirm and claim, one delivered operation. - - The transport owner must supply a verified callback envelope. A - successful confirmation consumes the operation in this transaction so - concurrent web/Lark clicks cannot both dispatch it. - """ - - selected_decision = str(decision or "").strip().lower() - if selected_decision not in {"confirm", "reject"}: - raise ValueError("operation decision must be confirm or reject") - safe_confirmation = _safe_json_value( - dict(confirmation), path="operation.confirmation" + confirmation: Mapping[str, object], + ) -> JsonDict: + """Atomically reject, or confirm and claim, one delivered operation.""" + return _operations.decide_operation( + self, proposal_id, decision=decision, confirmation=confirmation ) - if not isinstance(safe_confirmation, dict): - raise ValueError("operation confirmation must be an object") - required = { - "provider", - "event_id", - "principal", - "message_id", - "chat_id", - "app_id", - "surface_kind", - "interaction_kind", - "confirmation_digest", - "card_digest", - "confirmed_at", - "actor_class", - "verification_kind", - } - if set(safe_confirmation) != required: - raise ValueError("operation confirmation has unsupported or missing fields") - for field in required: - _bounded_text( - safe_confirmation.get(field), - field=f"operation.confirmation.{field}", - limit=512, - ) - if safe_confirmation["actor_class"] != HUMAN_ACTOR_CLASS: - raise ValueError("operation confirmation requires a human actor") - _opaque_id( - safe_confirmation["verification_kind"], - field="operation.confirmation.verification_kind", - ) - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="decide_operation", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - operation = ( - proposal.get("operation") if isinstance(proposal, dict) else None - ) - if not isinstance(operation, dict): - raise KeyError("typed operation was not found") - existing_confirmation = operation.get("confirmation") - if isinstance(existing_confirmation, dict): - if ( - existing_confirmation.get("event_id") - == safe_confirmation["event_id"] - ): - return proposal - raise ActionConflictError("operation already consumed another decision") - if ( - proposal.get("status") != "gated" - or operation.get("lifecycle_state") != "awaiting_confirmation" - ): - raise ActionConflictError("operation is not awaiting confirmation") - delivery = operation.get("delivery") - if not isinstance(delivery, dict): - raise ActionConflictError("operation card delivery is not verified") - expected = { - "provider": delivery.get("provider"), - "message_id": delivery.get("message_id"), - "chat_id": delivery.get("chat_id"), - "app_id": delivery.get("app_id"), - "card_digest": delivery.get("card_digest"), - "confirmation_digest": operation.get("confirmation_digest"), - } - if any( - safe_confirmation.get(field) != value - for field, value in expected.items() - ): - raise ActionConflictError( - "operation callback does not match the delivered request" - ) - if safe_confirmation.get("principal") not in set( - operation.get("authorized_principals") or [] - ): - raise ActionConflictError( - "principal is not authorized for this operation" - ) - expires_at = datetime.fromisoformat( - str(operation.get("expires_at") or "").replace("Z", "+00:00") - ) - confirmed_at = datetime.fromisoformat( - str(safe_confirmation["confirmed_at"]).replace("Z", "+00:00") - ) - delivered_at = datetime.fromisoformat( - str(delivery.get("delivered_at") or "").replace("Z", "+00:00") - ) - if ( - expires_at.tzinfo is None - or confirmed_at.tzinfo is None - or delivered_at.tzinfo is None - ): - raise ValueError("operation timestamps require a timezone") - if confirmed_at < delivered_at - timedelta(minutes=5): - raise ActionConflictError( - "operation confirmation predates the delivered request" - ) - if confirmed_at > expires_at: - raise ActionConflictError("operation confirmation arrived after expiry") - now = _utc_now() - now_at = datetime.fromisoformat(now.replace("Z", "+00:00")) - if confirmed_at > now_at + timedelta(minutes=5): - raise ActionConflictError( - "operation confirmation timestamp is in the future" - ) - operation["confirmation"] = { - **safe_confirmation, - "decision": selected_decision, - } - if selected_decision == "reject": - operation["lifecycle_state"] = "outcome_observed" - operation["outcome"] = { - "schema_version": "loopx_operation_outcome_v0", - "outcome": "rejected_by_operator", - "projection_verified": True, - "observed_at": now, - } - proposal["status"] = "rejected" - proposal["rejected_at"] = now - proposal["receipt"] = operation["outcome"] - else: - operation["lifecycle_state"] = "claimed" - operation["claim"] = { - "claim_id": "claim-" + uuid.uuid4().hex, - "event_id": safe_confirmation["event_id"], - "claimed_at": now, - } - proposal["status"] = "applying" - proposal["gate"] = None - proposal["updated_at"] = now - self._write(payload) - return proposal def observe_operation_outcome( self, proposal_id: str, *, - outcome: Mapping[str, Any], - agent_actor: Mapping[str, Any] | None = None, + outcome: Mapping[str, object], + agent_actor: Mapping[str, object] | None = None, agent_binding_current: bool = False, agent_actor_binding_current: bool = False, - ) -> dict[str, Any]: + ) -> JsonDict: """Persist the domain result without making it a retryable submission.""" - - safe_outcome = _safe_json_value(dict(outcome), path="operation.outcome") - if not isinstance(safe_outcome, dict): - raise ValueError("operation outcome must be an object") - if safe_outcome.get("schema_version") != "loopx_operation_outcome_v0": - raise ValueError("operation outcome schema is unsupported") - _opaque_id(safe_outcome.get("outcome"), field="operation.outcome.outcome") - if safe_outcome.get("projection_verified") is not True: - raise ValueError("operation outcome projection must be verified") - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="observe_operation_outcome", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - operation = ( - proposal.get("operation") if isinstance(proposal, dict) else None - ) - if not isinstance(operation, dict): - raise KeyError("typed operation was not found") - parameters = proposal.get("normalized_parameters") or {} - report_provenance = None - if (parameters.get("executor") or {}).get("kind") in {"agent_session", "managed_turn"}: - plan = self._agent_operation_plan( - proposal, - action="report", - actor=agent_actor, - binding_current=agent_binding_current, - actor_binding_current=agent_actor_binding_current, - outcome=safe_outcome, - ) - report_provenance = plan["report_provenance"] - if plan.get("write_reconciliation") is True: - existing = operation.get("reconciliation") - if existing is not None: - if existing != safe_outcome: - raise ActionConflictError( - "operation reconciliation is already immutable" - ) - return proposal - operation["reconciliation"] = safe_outcome - operation["reconciliation_report"] = report_provenance - proposal["receipt"] = safe_outcome - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal - if operation.get("lifecycle_state") == "outcome_observed": - if operation.get("outcome") != safe_outcome: - raise ActionConflictError("operation outcome is already immutable") - return proposal - if ( - operation.get("lifecycle_state") != "claimed" - or proposal.get("status") != "applying" - ): - raise ActionConflictError( - "only a claimed operation can record an outcome" - ) - now = _utc_now() - operation["lifecycle_state"] = "outcome_observed" - operation["outcome"] = safe_outcome - if report_provenance is not None: - operation["outcome_report"] = report_provenance - proposal["status"] = "applied" - proposal["receipt"] = safe_outcome - proposal["applied_at"] = now - proposal["updated_at"] = now - self._write(payload) - return proposal + return _operations.observe_operation_outcome( + self, + proposal_id, + outcome=outcome, + agent_actor=agent_actor, + agent_binding_current=agent_binding_current, + agent_actor_binding_current=agent_actor_binding_current, + ) @staticmethod def _agent_operation_plan( - proposal: Mapping[str, Any], **request: Any - ) -> dict[str, Any]: + proposal: Mapping[str, object], **request: object + ) -> JsonDict: """One typed decision, using the existing canonical JSON byte format.""" - from .control_plane.effect_runtime import ( - EffectRuntimeRemoteError, - effect_runtime_result, - ) - - parameters = proposal.get("normalized_parameters") or {} - digests = { - "payload_digest": _canonical_digest(parameters.get("payload") or {}), - "projection_digest": _canonical_digest(parameters.get("projection") or {}), - "confirmation_digest": _canonical_digest( - { - "action_kind": "operation.execute", - "normalized_parameters": parameters, - "request_digest": proposal.get("request_digest"), - } - ), - "outcome_digest": _canonical_digest(proposal["operation"]["outcome"]) - if isinstance((proposal.get("operation") or {}).get("outcome"), dict) - else None, - } - try: - return dict( - effect_runtime_result( - "operation.agent_handoff.plan", - { - "proposal": dict(proposal), - "digests": digests, - "now": _utc_now(), - **request, - }, - ) - ) - except EffectRuntimeRemoteError as exc: - raise ActionConflictError(str(exc)) from exc + return _operations.agent_operation_plan(proposal, **request) def reserve_agent_operation_turn( - self, proposal_id: str, **launch_context: Any, - ) -> dict[str, Any]: - """Internal callback launch intent. - - Commit before spawning. A lost/failed spawn is reconciled from the - original Turn; callback replay never launches a replacement process. - """ - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock(self.path, operation="reserve_operation_turn"): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed operation was not found") - plan = self._agent_operation_plan(proposal, action="wake", **launch_context) - receipt = plan.pop("write_turn_launch", None) - if receipt is not None: - proposal["operation"]["turn_launch"] = receipt - proposal["updated_at"] = _utc_now() - self._write(payload) - plan["turn_launch"] = receipt - return plan + self, proposal_id: str, **launch_context: object + ) -> JsonDict: + """Internal callback launch intent.""" + return _operations.reserve_agent_operation_turn( + self, proposal_id, **launch_context + ) def record_agent_operation_host_start( - self, proposal_id: str, *, actor: Mapping[str, Any], - binding_current: bool, turn_key: str, - ) -> dict[str, Any]: + self, + proposal_id: str, + *, + actor: Mapping[str, object], + binding_current: bool, + turn_key: str, + ) -> JsonDict: """Internal native transport observation; never a caller proof or permit.""" - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock(self.path, operation="observe_operation_host_start"): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed operation was not found") - plan = self._agent_operation_plan( - proposal, action="observe_host_start", actor=dict(actor), - binding_current=binding_current, turn_key=turn_key, - ) - receipt = plan.pop("write_host_start", None) - if receipt is not None: - proposal["operation"]["host_start"] = receipt - proposal["updated_at"] = _utc_now() - self._write(payload) - plan.update(host_start=receipt, host_delivery="native_start_accepted") - return plan + return _operations.record_agent_operation_host_start( + self, + proposal_id, + actor=actor, + binding_current=binding_current, + turn_key=turn_key, + ) def consume_agent_operation( self, proposal_id: str, *, - actor: Mapping[str, Any], + actor: Mapping[str, object], binding_current: bool, consumption_id: str, - ) -> dict[str, Any]: + ) -> JsonDict: """Commit before external execution. Even an exact replay grants no retry.""" - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, agent_id="loopx-chat", operation="consume_agent_operation" - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed operation was not found") - plan = self._agent_operation_plan( - proposal, - action="consume", - actor=dict(actor), - binding_current=binding_current, - consumption_id=consumption_id, - ) - handoff = plan.pop("write_handoff", None) - if handoff is not None: - proposal["operation"]["agent_handoff"] = handoff - proposal["updated_at"] = _utc_now() - self._write(payload) - plan["consumption_id"] = handoff["consumption_id"] - return plan + return _operations.consume_agent_operation( + self, + proposal_id, + actor=actor, + binding_current=binding_current, + consumption_id=consumption_id, + ) def record_operation_result_delivery( - self, - proposal_id: str, - *, - delivery: Mapping[str, Any], - ) -> dict[str, Any]: + self, proposal_id: str, *, delivery: Mapping[str, object] + ) -> JsonDict: """Persist exact result-card readback without changing domain outcome.""" - - safe_delivery = _safe_json_value( - dict(delivery), path="operation.result_delivery" + return _operations.record_operation_result_delivery( + self, proposal_id, delivery=delivery ) - if not isinstance(safe_delivery, dict): - raise ValueError("operation result delivery must be an object") - required = { - "provider", - "message_id", - "chat_id", - "app_id", - "card_digest", - "transport", - "delivered_at", - } - if set(safe_delivery) not in (required, required | {"outcome_stage"}): - raise ValueError( - "operation result delivery has unsupported or missing fields" - ) - for field in required: - _bounded_text( - safe_delivery.get(field), - field=f"operation.result_delivery.{field}", - limit=512, - ) - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="record_operation_result_delivery", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - operation = ( - proposal.get("operation") if isinstance(proposal, dict) else None - ) - if not isinstance(operation, dict): - raise KeyError("typed operation was not found") - if operation.get("lifecycle_state") != "outcome_observed": - raise ActionConflictError( - "operation outcome is unavailable for result delivery" - ) - is_agent = ( - (proposal.get("normalized_parameters") or {}).get("executor") or {} - ).get("kind") in {"agent_session", "managed_turn"} - expected_stage = ( - "reconciled" - if operation.get("reconciliation") is not None - else "initial" - ) - if is_agent and safe_delivery.get("outcome_stage") != expected_stage: - raise ActionConflictError( - "result delivery is not for the current operation outcome" - ) - if not is_agent and "outcome_stage" in safe_delivery: - raise ValueError( - "result outcome stage is only supported for Agent handoff" - ) - source_delivery = operation.get("delivery") - if not isinstance(source_delivery, dict) or any( - safe_delivery.get(field) != source_delivery.get(field) - for field in ("provider", "message_id", "chat_id", "app_id") - ): - raise ActionConflictError( - "operation result delivery does not match the original card" - ) - existing = operation.get("result_delivery") - if isinstance(existing, dict): - if existing != safe_delivery: - if not ( - is_agent - and existing.get("outcome_stage") == "initial" - and expected_stage == "reconciled" - ): - raise ActionConflictError( - "operation result delivery is already immutable" - ) - else: - return proposal - operation["result_delivery"] = safe_delivery - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal - def load(self, proposal_id: str) -> dict[str, Any] | None: + def load(self, proposal_id: str) -> JsonDict | None: token = _opaque_id(proposal_id, field="proposal_id") - proposal = self._read()["proposals"].get(token) + proposal = store_proposals(self._read()).get(token) if proposal is None: return None - if ( - not isinstance(proposal, dict) - or proposal.get("status") not in PROPOSAL_STATES - ): + if not is_str_dict(proposal) or proposal.get("status") not in PROPOSAL_STATES: raise ValueError("typed Chat action proposal is malformed") return proposal @@ -1369,83 +429,16 @@ def list( goal_id: str | None = None, context_kind: str | None = None, status: str | None = None, - ) -> list[dict[str, Any]]: - selected_goal = _opaque_id(goal_id, field="goal_id") if goal_id else None - selected_context = ( - _opaque_id(context_kind, field="context_kind") if context_kind else None - ) - if status and status not in PROPOSAL_STATES: - raise ValueError("status must be a supported typed action state") - proposals: list[dict[str, Any]] = [] - for raw in self._read()["proposals"].values(): - if not isinstance(raw, dict) or raw.get("status") not in PROPOSAL_STATES: - continue - context = raw.get("context") - context = context if isinstance(context, dict) else {} - parameters = raw.get("normalized_parameters") - parameters = parameters if isinstance(parameters, dict) else {} - proposal_goal = str( - context.get("goal_id") or parameters.get("goal_id") or "" - ) - if selected_goal and proposal_goal != selected_goal: - continue - if selected_context and str(context.get("kind") or "") != selected_context: - continue - if status and raw.get("status") != status: - continue - proposals.append(raw) - return sorted( - proposals, - key=lambda proposal: ( - str(proposal.get("updated_at") or ""), - str(proposal.get("proposal_id") or ""), - ), - reverse=True, + ) -> list[JsonDict]: + return _common.list_proposals( + self, goal_id=goal_id, context_kind=context_kind, status=status ) - def cancel(self, proposal_id: str) -> dict[str, Any]: - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="cancel_chat_action_preview", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - if proposal.get("status") == "cancelled": - return proposal - if proposal.get("status") not in { - "preview_ready", - "gated", - "failed", - "deferred", - }: - raise ActionConflictError( - f"proposal in {proposal.get('status')} state cannot be cancelled" - ) - now = _utc_now() - proposal["status"] = "cancelled" - proposal["cancelled_at"] = now - operation = proposal.get("operation") - if isinstance(operation, dict): - operation["lifecycle_state"] = "outcome_observed" - operation["outcome"] = { - "schema_version": "loopx_operation_outcome_v0", - "outcome": "cancelled_before_confirmation", - "projection_verified": True, - "observed_at": now, - } - proposal["receipt"] = operation["outcome"] - proposal["gate"] = None - proposal["updated_at"] = now - self._write(payload) - return proposal + def cancel(self, proposal_id: str) -> JsonDict: + return _common.cancel_proposal(self, proposal_id) - def start_apply(self, proposal_id: str) -> dict[str, Any]: + def start_apply(self, proposal_id: str) -> JsonDict: """Persist the execution boundary before any canonical write is attempted.""" - return self._transition( proposal_id, from_states=RETRYABLE_PROPOSAL_STATES, @@ -1455,11 +448,9 @@ def start_apply(self, proposal_id: str) -> dict[str, Any]: ) def mark_gated( - self, proposal_id: str, *, gate: Mapping[str, Any] - ) -> dict[str, Any]: - safe_gate = _safe_json_value(dict(gate), path="gate") - if not isinstance(safe_gate, dict): - raise ValueError("gate must be an object") + self, proposal_id: str, *, gate: Mapping[str, object] + ) -> JsonDict: + safe_gate = safe_object_dict(gate, path="gate", label="gate") _opaque_id(safe_gate.get("kind"), field="gate.kind") return self._transition( proposal_id, @@ -1475,12 +466,12 @@ def mark_failed( *, error_code: str, message: str, - details: Mapping[str, Any] | None = None, - ) -> dict[str, Any]: + details: Mapping[str, object] | None = None, + ) -> JsonDict: # A failure that happened after part of the work was committed has to # carry those identities, or the retry cannot tell what already exists # and the owner has to reconstruct it from the message. - record: dict[str, Any] = { + record: JsonDict = { "error_code": _opaque_id(error_code, field="error_code"), "message": _bounded_text(message, field="message", limit=1000), "failed_at": _utc_now(), @@ -1502,42 +493,13 @@ def save_checkpoint( proposal_id: str, *, step: str, - receipt: Mapping[str, Any], - ) -> dict[str, Any]: - safe_step = _opaque_id(step, field="step") - safe_receipt = _safe_json_value(dict(receipt), path="checkpoint.receipt") - if not isinstance(safe_receipt, dict): - raise ValueError("checkpoint receipt must be an object") - token = _opaque_id(proposal_id, field="proposal_id") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="checkpoint_chat_action_preview", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - if proposal.get("status") not in {"applying", "gated", "failed"}: - raise ActionConflictError( - f"proposal in {proposal.get('status')} state cannot save a checkpoint" - ) - checkpoint = proposal.get("checkpoint") - checkpoint = ( - dict(checkpoint) if isinstance(checkpoint, dict) else {"steps": {}} - ) - steps = checkpoint.get("steps") - steps = dict(steps) if isinstance(steps, dict) else {} - steps[safe_step] = safe_receipt - checkpoint["steps"] = steps - checkpoint["last_completed_step"] = safe_step - checkpoint["updated_at"] = _utc_now() - proposal["checkpoint"] = checkpoint - proposal["updated_at"] = checkpoint["updated_at"] - self._write(payload) - return proposal + receipt: Mapping[str, object], + ) -> JsonDict: + return _common.save_proposal_checkpoint( + self, proposal_id, step=step, receipt=receipt + ) - def mark_rejected(self, proposal_id: str) -> dict[str, Any]: + def mark_rejected(self, proposal_id: str) -> JsonDict: now = _utc_now() return self._transition( proposal_id, @@ -1547,7 +509,7 @@ def mark_rejected(self, proposal_id: str) -> dict[str, Any]: idempotent_states={"rejected"}, ) - def mark_deferred(self, proposal_id: str) -> dict[str, Any]: + def mark_deferred(self, proposal_id: str) -> JsonDict: now = _utc_now() return self._transition( proposal_id, @@ -1559,7 +521,7 @@ def mark_deferred(self, proposal_id: str) -> dict[str, Any]: def link_regeneration( self, proposal_id: str, *, regenerated_from: str - ) -> dict[str, Any]: + ) -> JsonDict: token = _opaque_id(proposal_id, field="proposal_id") source = _opaque_id(regenerated_from, field="regenerated_from") with exclusive_file_lock( @@ -1568,13 +530,9 @@ def link_regeneration( operation="link_chat_action_regeneration", ): payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") + proposal = _common.require_proposal(payload, token) proposal["regenerated_from"] = source - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal + return _common.commit_proposal_mutation(self, payload, proposal) def _transition( self, @@ -1582,86 +540,28 @@ def _transition( *, from_states: set[str], to_state: str, - updates: Mapping[str, Any], + updates: Mapping[str, object], idempotent_states: set[str], - ) -> dict[str, Any]: - token = _opaque_id(proposal_id, field="proposal_id") - if to_state not in PROPOSAL_STATES: - raise ValueError("unsupported typed action state") - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation=f"transition_chat_action_{to_state}", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - status = str(proposal.get("status") or "") - if status in idempotent_states: - return proposal - if status not in from_states: - raise ActionConflictError( - f"proposal in {status} state cannot become {to_state}" - ) - proposal["status"] = to_state - proposal.update(_safe_json_value(dict(updates), path="transition")) - proposal["updated_at"] = _utc_now() - self._write(payload) - return proposal + ) -> JsonDict: + return _common.transition_proposal( + self, + proposal_id, + from_states=from_states, + to_state=to_state, + updates=updates, + idempotent_states=idempotent_states, + ) def apply( self, proposal_id: str, *, current_state_fingerprint: str, - receipt: Mapping[str, Any], - ) -> dict[str, Any]: - token = _opaque_id(proposal_id, field="proposal_id") - current_fingerprint = _bounded_text( - current_state_fingerprint, - field="current_state_fingerprint", - limit=512, + receipt: Mapping[str, object], + ) -> JsonDict: + return _common.apply_proposal( + self, + proposal_id, + current_state_fingerprint=current_state_fingerprint, + receipt=receipt, ) - with exclusive_file_lock( - self.path, - agent_id="loopx-chat", - operation="apply_chat_action_preview", - ): - payload = self._read() - proposal = payload["proposals"].get(token) - if not isinstance(proposal, dict): - raise KeyError("typed Chat action proposal was not found") - status = str(proposal.get("status") or "") - if status == "applied": - return proposal - if status not in {"preview_ready", "applying"}: - raise ActionConflictError( - f"proposal in {status} state cannot be applied" - ) - expected_fingerprint = str(proposal.get("expected_state_fingerprint") or "") - now = _utc_now() - if current_fingerprint != expected_fingerprint: - proposal["status"] = "stale" - proposal["stale"] = { - "expected_state_fingerprint": expected_fingerprint, - "current_state_fingerprint": current_fingerprint, - "detected_at": now, - } - proposal["updated_at"] = now - self._write(payload) - return proposal - - safe_receipt = _safe_json_value(dict(receipt), path="receipt") - if not isinstance(safe_receipt, dict): - raise ValueError("receipt must be an object") - _opaque_id(safe_receipt.get("receipt_id"), field="receipt.receipt_id") - _opaque_id(safe_receipt.get("outcome"), field="receipt.outcome") - if safe_receipt.get("projection_verified") is not True: - raise ValueError("receipt.projection_verified must be true") - proposal["status"] = "applied" - proposal["receipt"] = safe_receipt - proposal["applied_at"] = now - proposal["updated_at"] = now - self._write(payload) - return proposal diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py index d32ce522a7..8f261714ef 100644 --- a/loopx/chat_actions.py +++ b/loopx/chat_actions.py @@ -1577,7 +1577,7 @@ def _apply_owner_action(self, proposal_id: str, *, steward_context: dict[str, ob "proposal": proposal, "turn": self._turn_from_receipt(proposal.get("receipt")), } - if (proposal.get("context") or {}).get("binding_id"): + if _as_dict(proposal.get("context")).get("binding_id"): if steward_context is None: raise ProtectedActionGate(str(proposal["action_kind"]), gate={"kind": "authenticated_steward_confirmation_required", "summary": "Confirm this proposal from its original owner private conversation.", diff --git a/loopx/control_plane/collaboration/operation_handoff.py b/loopx/control_plane/collaboration/operation_handoff.py index 40c4b8fa76..ac623765be 100644 --- a/loopx/control_plane/collaboration/operation_handoff.py +++ b/loopx/control_plane/collaboration/operation_handoff.py @@ -96,8 +96,10 @@ def pending_operation_handoffs( return {"items": [], "pending_count": 0, "overflow": None, "next_cursor": None} result = [] for proposal in store.list(goal_id=goal_id) if store is not None else []: - parameters = proposal.get("normalized_parameters") or {} - executor = parameters.get("executor") or {} + raw_parameters = proposal.get("normalized_parameters") + parameters = dict(raw_parameters) if isinstance(raw_parameters, Mapping) else {} + raw_executor = parameters.get("executor") + executor = dict(raw_executor) if isinstance(raw_executor, Mapping) else {} if ( proposal.get("action_kind") != "operation.execute" or parameters.get("agent_id") != agent_id @@ -193,7 +195,8 @@ def agent_operation_action( proposal = store.load(proposal_id) if proposal is None: raise ValueError("canonical operation was not found") - parameters = proposal.get("normalized_parameters") or {} + raw_parameters = proposal.get("normalized_parameters") + parameters = dict(raw_parameters) if isinstance(raw_parameters, Mapping) else {} if (parameters.get("goal_id"), parameters.get("agent_id")) != ( actor.get("goal_id"), actor.get("agent_id"), @@ -346,12 +349,13 @@ def _commit_agent_operation( agent_actor_binding_current=actor_current, ) plan = store._agent_operation_plan(updated, action="project") + raw_operation = updated.get("operation") + operation = dict(raw_operation) if isinstance(raw_operation, Mapping) else {} return { "ok": True, **plan, - "outcome": updated["operation"].get("reconciliation") - or updated["operation"]["outcome"], - "outcome_report": updated["operation"].get("outcome_report"), - "reconciliation_report": updated["operation"].get("reconciliation_report"), + "outcome": operation.get("reconciliation") or operation.get("outcome"), + "outcome_report": operation.get("outcome_report"), + "reconciliation_report": operation.get("reconciliation_report"), } raise ValueError("unsupported agent operation action") diff --git a/loopx/control_plane/goals/acceptance_actions.py b/loopx/control_plane/goals/acceptance_actions.py index 2f98885d90..8d2802a3a2 100644 --- a/loopx/control_plane/goals/acceptance_actions.py +++ b/loopx/control_plane/goals/acceptance_actions.py @@ -7,6 +7,7 @@ from __future__ import annotations +from collections.abc import Mapping import json from pathlib import Path from typing import Any @@ -45,9 +46,11 @@ def _saved_check(store: ChatActionStore, parameters: dict[str, Any], for proposal in store.list(goal_id=parameters["goal_id"], context_kind="goal"): if proposal["idempotency_key"] != operation_id: continue + raw_params = proposal["normalized_parameters"] if (proposal["action_kind"] != "goal.acceptance.check" or proposal["context"] != {"kind": "goal", "goal_id": parameters["goal_id"]} - or {key: value for key, value in proposal["normalized_parameters"].items() + or not isinstance(raw_params, Mapping) + or {key: value for key, value in raw_params.items() if key != "resolved_document"} not in accepted_intents): raise ActionConflictError("The operation belongs to another check request") return proposal @@ -132,13 +135,23 @@ def _apply_acceptance_check(self, proposal_id: str) -> dict[str, Any]: raise KeyError("Check plan was not found") if proposal["status"] == "applied": return {"proposal": proposal, "turn": None} - parameters = proposal["normalized_parameters"] + raw_params = proposal["normalized_parameters"] + if not isinstance(raw_params, Mapping): + raise ValueError("Check plan parameters are malformed") + parameters = dict(raw_params) route = self._acceptance_route(parameters["goal_id"]) - steps = (proposal.get("checkpoint") or {}).get("steps", {}) + raw_checkpoint = proposal.get("checkpoint") + raw_steps = ( + raw_checkpoint.get("steps", {}) + if isinstance(raw_checkpoint, Mapping) + else {} + ) + steps = raw_steps if isinstance(raw_steps, Mapping) else {} configured = steps.get("acceptance_configured") operation_id = f"acceptance-check:{proposal_id}" + expected_fingerprint = str(proposal["expected_state_fingerprint"]) if configured is None: - basis = _review_basis(proposal["expected_state_fingerprint"]) + basis = _review_basis(expected_fingerprint) expected = basis["provider_revision"] try: # Its native idempotency receipt also recovers a lost @@ -188,5 +201,5 @@ def _apply_acceptance_check(self, proposal_id: str) -> dict[str, Any]: "projection_verified": True, "goal_id": parameters["goal_id"], "operation_id": operation_id, "checks_passed": result["checks_passed"]} stored = self.store.apply(proposal_id, - current_state_fingerprint=proposal["expected_state_fingerprint"], receipt=receipt) + current_state_fingerprint=expected_fingerprint, receipt=receipt) return {"proposal": stored, "turn": None} diff --git a/loopx/control_plane/goals/goal_objective_actions.py b/loopx/control_plane/goals/goal_objective_actions.py index 009f5fa07f..8ec3edde0c 100644 --- a/loopx/control_plane/goals/goal_objective_actions.py +++ b/loopx/control_plane/goals/goal_objective_actions.py @@ -55,11 +55,14 @@ def objective_revision_proposal(*, registry_path: Path, runtime_root: str | None proposal = service.load(proposal_id) if proposal is None: raise ValueError("Objective proposal was not found") - parameters = proposal["normalized_parameters"] + raw_parameters = proposal["normalized_parameters"] + raw_context = proposal["context"] if (proposal["action_kind"] != "goal.update" - or proposal["context"].get("goal_id") != goal_id - or parameters.get("goal_id") != goal_id - or not {"objective", "reason", "source_ref"}.issubset(parameters)): + or not isinstance(raw_context, Mapping) + or not isinstance(raw_parameters, Mapping) + or raw_context.get("goal_id") != goal_id + or raw_parameters.get("goal_id") != goal_id + or not {"objective", "reason", "source_ref"}.issubset(raw_parameters)): raise ValueError("Proposal is not a current-objective revision for this Goal") if not execute: return {"ok": True, "executed": False, "proposal": proposal, @@ -195,12 +198,22 @@ def _apply_objective_revision(self, proposal_id: str) -> dict[str, Any]: raise KeyError("Objective proposal is unavailable") if proposal["status"] == "applied": return {"proposal": proposal, "turn": None} - parameters = proposal["normalized_parameters"] - basis = json.loads(proposal["expected_state_fingerprint"]) + raw_parameters = proposal["normalized_parameters"] + if not isinstance(raw_parameters, Mapping): + raise ValueError("Objective proposal parameters are malformed") + parameters = dict(raw_parameters) + expected_fingerprint = str(proposal["expected_state_fingerprint"]) + basis = json.loads(expected_fingerprint) document = {key: parameters[key] for key in ("objective", "reason", "source_ref")} # Retain exactly the native request before its first attempt. A # missing reply retries that operation, never creates another edit. - steps = (proposal.get("checkpoint") or {}).get("steps", {}) + raw_checkpoint = proposal.get("checkpoint") + raw_steps = ( + raw_checkpoint.get("steps", {}) + if isinstance(raw_checkpoint, Mapping) + else {} + ) + steps = raw_steps if isinstance(raw_steps, Mapping) else {} if not steps.get("objective_started"): fingerprint, _ = self._objective_preview(parameters) if json.loads(fingerprint)["objective_digest"] != basis["objective_digest"]: @@ -213,5 +226,5 @@ def _apply_objective_revision(self, proposal_id: str) -> dict[str, Any]: current = inspect_goal_acceptance(**self._objective_route(parameters["goal_id"])) receipt = {"receipt_id": f"objective-{proposal_id}", "outcome": "objective_revised", "projection_verified": True, "goal_id": parameters["goal_id"], "operation_id": saved["operation_id"]} - stored = self.store.apply(proposal_id, current_state_fingerprint=proposal["expected_state_fingerprint"], receipt=receipt) + stored = self.store.apply(proposal_id, current_state_fingerprint=expected_fingerprint, receipt=receipt) return {"proposal": stored, "turn": None, "current": public_goal_acceptance(current)} diff --git a/loopx/control_plane/turn_driver/managed_operation_host.py b/loopx/control_plane/turn_driver/managed_operation_host.py index 94eb6bde15..0dca2d6189 100644 --- a/loopx/control_plane/turn_driver/managed_operation_host.py +++ b/loopx/control_plane/turn_driver/managed_operation_host.py @@ -250,6 +250,8 @@ def require_confirmed_operation_resume( else "confirmed operation requires its original resumable session" ) parameters = proposal["normalized_parameters"] + if not isinstance(parameters, Mapping): + raise ValueError("confirmed operation parameters are malformed") require_current_operation_scope(registry_path, parameters) store._agent_operation_plan( proposal, action="wake", diff --git a/loopx/extensions/lark/goal_channel_operation.py b/loopx/extensions/lark/goal_channel_operation.py index cb6f7fd650..21c104e45b 100644 --- a/loopx/extensions/lark/goal_channel_operation.py +++ b/loopx/extensions/lark/goal_channel_operation.py @@ -1126,6 +1126,7 @@ def handle_goal_channel_operation_callback( if current is None: raise ValueError("operation disappeared before result delivery") decided = current + _, decided_operation = _proposal_operation(decided) result_card = build_goal_channel_operation_result_card(decided) if _result_delivery_current(decided): update = {"external_write_performed": False, "readback_verified": True} @@ -1142,7 +1143,7 @@ def handle_goal_channel_operation_callback( ) if ( update["readback_verified"] is True - and decided["operation"]["lifecycle_state"] == "outcome_observed" + and decided_operation.get("lifecycle_state") == "outcome_observed" ): decided = store.record_operation_result_delivery( action["operation_id"], @@ -1157,10 +1158,11 @@ def handle_goal_channel_operation_callback( **_result_delivery_stage(decided), }, ) + _, decided_operation = _proposal_operation(decided) update_verified = update["readback_verified"] observed_outcome = ( - decided["operation"].get("reconciliation") - or decided["operation"].get("outcome") + decided_operation.get("reconciliation") + or decided_operation.get("outcome") or {} ) return { @@ -1168,11 +1170,11 @@ def handle_goal_channel_operation_callback( "schema_version": OPERATION_CALLBACK_RECEIPT_SCHEMA_VERSION, "operation_id": action["operation_id"], "decision": action["decision"], - "lifecycle_state": decided["operation"]["lifecycle_state"], + "lifecycle_state": decided_operation["lifecycle_state"], "outcome": observed_outcome.get("outcome"), "claim_id": ( - decided["operation"]["claim"]["claim_id"] - if isinstance(decided["operation"].get("claim"), Mapping) + decided_operation["claim"]["claim_id"] + if isinstance(decided_operation.get("claim"), Mapping) else None ), "callback_ack_is_execution_receipt": False, @@ -1180,7 +1182,7 @@ def handle_goal_channel_operation_callback( "card_update_verified": update_verified, "status": ( "authorization_pending" - if decided["operation"]["lifecycle_state"] == "claimed" + if decided_operation["lifecycle_state"] == "claimed" else "submission_unknown" if observed_outcome.get("outcome") == "submission_unknown" else "outcome_observed" diff --git a/tests/test_chat_action_store_contract.py b/tests/test_chat_action_store_contract.py new file mode 100644 index 0000000000..57cabb70f8 --- /dev/null +++ b/tests/test_chat_action_store_contract.py @@ -0,0 +1,255 @@ +"""Contract and modularization tests for Zero-Any ChatActionStore modules.""" + +from __future__ import annotations + +import ast +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +import pytest + +from loopx import chat_action_store +from loopx.chat_action_store import ( + ACTION_KINDS, + HUMAN_ACTOR_CLASS, + ActionConflictError, + ChatActionStore, + _OPAQUE_ID, + _bounded_text, + _canonical_digest, + _opaque_id, + _safe_json_value, + _utc_now, + atomic_write_json, + exclusive_file_lock, + normalize_idempotency_key, +) + + +def test_chat_action_store_modularization_zero_any_and_exports() -> None: + root = Path(__file__).resolve().parents[1] / "loopx" + limits = { + "chat_action_store.py": 650, + "chat/action_store_common.py": 700, + "chat/action_store_review_cards.py": 700, + "chat/action_store_operations.py": 700, + } + for filename, max_lines in limits.items(): + source = (root / filename).read_text(encoding="utf-8") + tree = ast.parse(source) + any_refs = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Name) and node.id == "Any" + ] + assert any_refs == [], f"{filename} must remain Zero-Any" + assert "type: ignore" not in source + assert "O_NOFOLLOW" not in source + assert len(source.splitlines()) < max_lines + + assert callable(_utc_now) + assert callable(_opaque_id) + assert callable(normalize_idempotency_key) + assert callable(_bounded_text) + assert callable(_safe_json_value) + assert callable(_canonical_digest) + assert callable(atomic_write_json) + assert callable(exclusive_file_lock) + assert isinstance(ACTION_KINDS, set) + assert _OPAQUE_ID.fullmatch("proposal_1") + + +def test_store_monkeypatch_hooks_propagate_across_submodules( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + stamps = iter( + [ + "2026-11-26T00:00:01Z", + "2026-11-26T00:00:02Z", + "2026-11-26T00:00:03Z", + "2026-11-26T00:00:04Z", + "2026-11-26T00:00:05Z", + "2026-11-26T00:00:06Z", + "2026-11-26T00:00:07Z", + "2026-11-26T00:00:08Z", + "2026-11-26T00:00:09Z", + "2026-11-26T00:00:10Z", + ] + ) + lock_calls: list[tuple[str | None, str | None]] = [] + real_lock = chat_action_store.exclusive_file_lock + + @contextmanager + def spy_lock(path: Path, **kwargs: object) -> Iterator[Path]: + agent_id = kwargs.get("agent_id") + operation = kwargs.get("operation") + lock_calls.append( + ( + str(agent_id) if agent_id is not None else None, + str(operation) if operation is not None else None, + ) + ) + with real_lock( + path, + agent_id=str(agent_id) if isinstance(agent_id, str) else None, + operation=str(operation) if isinstance(operation, str) else None, + ) as locked: + yield locked + + monkeypatch.setattr("loopx.chat_action_store._utc_now", lambda: next(stamps)) + monkeypatch.setattr(chat_action_store, "exclusive_file_lock", spy_lock) + write_paths: list[Path] = [] + real_write = chat_action_store.atomic_write_json + + def spy_write( + path: Path, payload: dict[str, object], *, preserve_mode: bool = False + ) -> None: + write_paths.append(path) + real_write(path, payload, preserve_mode=preserve_mode) + + monkeypatch.setattr(chat_action_store, "atomic_write_json", spy_write) + + store = ChatActionStore(tmp_path / "actions") + assert len(write_paths) == 1 + preview = store.create_preview( + action_kind="team.plan", + summary="Confirm team plan", + normalized_parameters={"goal_id": "goal_1"}, + context={"kind": "goal", "goal_id": "goal_1"}, + expected_state_fingerprint="fp-1", + permission_classification="owner_only", + validation_evidence=["ok"], + available_transitions=["apply", "cancel"], + idempotency_key="idem-plan-1", + ) + assert preview["created_at"] == "2026-11-26T00:00:01Z" + + proposal_id = str(preview["proposal_id"]) + prepared = store.prepare_review_card_delivery( + proposal_id, audience_ids=["aud_a", "aud_b"], authorized_principal="user_1" + ) + assert prepared["updated_at"] == "2026-11-26T00:00:02Z" + + card = {"title": "Plan"} + card_digest = _canonical_digest(card) + for audience, msg_id in (("aud_a", "om_a"), ("aud_b", "om_b")): + store.record_review_card_delivery( + proposal_id, + audience_id=audience, + delivery={ + "provider": "lark", + "message_id": msg_id, + "chat_id": "oc_1", + "app_id": "cli_1", + "cli_bin": "lark-cli", + "sender_profile": "default", + "binding_digest": "bind_1", + "card_digest": card_digest, + "submitted_card": card, + "delivered_at": "2026-11-26T00:00:02Z", + "authorized_principal": "user_1", + }, + ) + + decided = store.decide_review_card( + proposal_id, + decision="confirm", + confirmation={ + "provider": "lark", + "event_id": "evt_1", + "principal": "user_1", + "message_id": "om_a", + "chat_id": "oc_1", + "app_id": "cli_1", + "audience_id": "aud_a", + "state_fingerprint": "fp-1", + "card_digest": card_digest, + "confirmed_at": "2026-11-26T00:00:05Z", + "actor_class": HUMAN_ACTOR_CLASS, + "verification_kind": "callback_sig", + }, + ) + assert decided["status"] == "applying" + assert decided["updated_at"] == "2026-11-26T00:00:05Z" + + recorded = store.record_review_card_result_delivery( + proposal_id, + audience_id="aud_a", + result={ + "card_digest": "res_1", + "transport": "callback_update", + "delivered_at": "2026-11-26T00:00:06Z", + }, + ) + assert recorded["updated_at"] == "2026-11-26T00:00:06Z" + assert ("loopx-chat", "decide_review_card") in lock_calls + assert ("loopx-chat", "record_review_card_result_delivery") in lock_calls + assert len(write_paths) >= 7 + + +def test_operation_replay_cancel_and_stale_transitions(tmp_path: Path) -> None: + store = ChatActionStore(tmp_path / "actions") + preview = store.create_preview( + action_kind="operation.execute", + summary="Run transfer", + normalized_parameters={ + "goal_id": "goal_1", + "expires_at": "2099-01-01T00:00:00Z", + "authorized_principals": ["user_1"], + }, + context={"kind": "goal", "goal_id": "goal_1"}, + expected_state_fingerprint="fp-op", + permission_classification="operator_confirmed", + validation_evidence=["checked"], + available_transitions=["cancel"], + idempotency_key="op-key-1", + ) + proposal_id = str(preview["proposal_id"]) + + reused = store.replay_or_reuse_preview( + action_kind="operation.execute", + context={"kind": "goal", "goal_id": "goal_1"}, + normalized_parameters={ + "goal_id": "goal_1", + "expires_at": "2099-01-01T00:00:00Z", + "authorized_principals": ["user_1"], + }, + idempotency_key="op-key-2", + shared_fields=("goal_id",), + reusable_states={"preview_ready"}, + matches_review_basis=lambda fp: fp == "fp-op", + ) + assert reused is not None + assert reused["proposal_id"] == proposal_id + + armed = store.arm_operation(proposal_id) + assert armed["status"] == "gated" + + cancelled = store.cancel(proposal_id) + assert cancelled["status"] == "cancelled" + assert isinstance(cancelled["operation"], dict) + assert cancelled["operation"]["lifecycle_state"] == "outcome_observed" + assert cancelled["operation"]["outcome"]["outcome"] == "cancelled_before_confirmation" + + with pytest.raises(ActionConflictError): + store.mark_rejected(proposal_id) + + drift = store.create_preview( + action_kind="goal.update", + summary="Update objective", + normalized_parameters={"goal_id": "goal_1"}, + context={"kind": "goal", "goal_id": "goal_1"}, + expected_state_fingerprint="fp-expected", + permission_classification="owner_only", + validation_evidence=["ok"], + available_transitions=["apply"], + idempotency_key="goal-upd-1", + ) + stale = store.apply( + str(drift["proposal_id"]), + current_state_fingerprint="fp-other", + receipt={"receipt_id": "r_1", "outcome": "done", "projection_verified": True}, + ) + assert stale["status"] == "stale" + assert isinstance(stale["stale"], dict) + assert stale["stale"]["expected_state_fingerprint"] == "fp-expected"