# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-remote-a2a-task-state-transition-that-is-locally-legal-but-globally-unobservable.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-remote-a2a-task-state-transition-that-is-locally-legal-but-globally-unobservable.warrant.json
# Markdown SHA-256:   52da049adb7b04ec7d60835c519ec02e5173c1628344a9399cabfc4cb20ad04e
# Code AST SHA-256:   5924eeba92cae2e8f44aa53e76e640e366bb36bc1c086b3b39dd2fc310bf9b77
# Verified Classes:   LifecycleConformanceError, Role, LocalState, RemoteEvent, TaskMirror
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class LifecycleConformanceError(RuntimeError):
    """Raised when a remote TaskStatusUpdateEvent has no legal local predecessor edge
    and the instance is the task owner with a bounded terminal fallback available."""


class Role(Enum):
    OWNER = "owner"
    DELEGATE = "delegate"


class LocalState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


# Legal local edges. Note: no WORKING -> WORKING self-loop is admitted.
LEGAL_EDGES: set[tuple[LocalState, LocalState]] = {
    (LocalState.SUBMITTED, LocalState.WORKING),
    (LocalState.WORKING, LocalState.INPUT_REQUIRED),
    (LocalState.INPUT_REQUIRED, LocalState.WORKING),
    (LocalState.WORKING, LocalState.COMPLETED),
    (LocalState.WORKING, LocalState.FAILED),
    (LocalState.WORKING, LocalState.CANCELED),
    (LocalState.INPUT_REQUIRED, LocalState.FAILED),
    (LocalState.INPUT_REQUIRED, LocalState.CANCELED),
}


@dataclass
class RemoteEvent:
    state: str
    metadata: dict = field(default_factory=dict)
    final: bool = False


@dataclass
class TaskMirror:
    task_id: str
    role: Role
    local_state: LocalState = LocalState.SUBMITTED
    terminal_fallback_available: bool = False
    opaque_events: list[RemoteEvent] = field(default_factory=list)


def admit_transition(task: TaskMirror, event: RemoteEvent) -> LocalState:
    """Admit or reject a remote transition against the local lifecycle machine.

    Returns the new local state on acceptance. Raises LifecycleConformanceError
    only when the instance is the owner AND a bounded terminal fallback exists;
    otherwise records the event opaquely and holds the last classifiable state.
    """
    try:
        remote_state = LocalState(event.state)
    except ValueError:
        # Unknown enum member: never a local edge. Treat as opaque regardless of role.
        task.opaque_events.append(event)
        return task.local_state

    candidate = (task.local_state, remote_state)

    if candidate in LEGAL_EDGES:
        task.local_state = remote_state
        return remote_state

    # No legal local edge. Decide by role and fallback availability.
    if task.role is Role.OWNER and task.terminal_fallback_available:
        # Owner with a bounded fallback: reject, then the caller MUST issue
        # tasks/cancel and wait for ack before transitioning to FAILED.
        raise LifecycleConformanceError(
            f"task {task.task_id}: remote transition "
            f"{task.local_state.value} -> {remote_state.value} has no local edge; "
            f"owner must cancel before terminating"
        )

    # Delegate, or owner without bounded fallback: accept opaquely.
    # Preserve the raw event; do not fork the local machine.
    task.opaque_events.append(event)
    return task.local_state


def drive_task(task: TaskMirror, events: list[RemoteEvent]) -> LocalState:
    for event in events:
        state = admit_transition(task, event)
        if state in (LocalState.COMPLETED, LocalState.FAILED, LocalState.CANCELED):
            return state
    return task.local_state


# Trace of the observed failure: owner, no fallback, remote emits WORKING->WORKING
# with suspension metadata after local is already WORKING.
if __name__ == "__main__":
    t = TaskMirror(task_id="t-1", role=Role.OWNER, terminal_fallback_available=False)
    events = [
        RemoteEvent(state="working"),
        RemoteEvent(state="working", metadata={"suspension": "awaiting-input"}),
    ]
    # With no bounded fallback, the self-loop is recorded opaquely, not rejected.
    final = drive_task(t, events)
    assert final is LocalState.WORKING
    assert len(t.opaque_events) == 1

    # Now the misconfigured case: owner with fallback but no cancel issued.
    t2 = TaskMirror(task_id="t-2", role=Role.OWNER, terminal_fallback_available=True)
    t2.local_state = LocalState.WORKING
    try:
        admit_transition(t2, RemoteEvent(state="working", metadata={"suspension": "awaiting-input"}))
    except LifecycleConformanceError as e:
        # Correct behavior: raise, then caller must tasks/cancel and await ack.
        print(f"rejected: {e}")
    else:
        raise LifecycleConformanceError("expected rejection for owner with fallback")
