# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-task-whose-agent-card-advertises-a-taskstate-it-can-no-longer-legally-transition-into.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-task-whose-agent-card-advertises-a-taskstate-it-can-no-longer-legally-transition-into.warrant.json
# Markdown SHA-256:   778340d168441fe14ea9bdf421ea7345e925463f293feff493f3ce1c29a57ee4
# Code AST SHA-256:   13d4784b2dcd931308d57a02e6975f49cde418e01feda89109846b63c859cd22
# Verified Classes:   UnmodeledTransitionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnmodeledTransitionError(RuntimeError):
    """Raised when a signed artifact's taskState has no legal edge from the
    caller's current local state, and the re-fetched Agent Card does not
    legitimize it either."""
    pass


# Caller's local machine: state -> set of legal successor states.
# Deliberately a superset of the happy path to absorb remote drains.
LEGAL_EDGES = {
    "submitted":       {"working", "rejected", "canceled"},
    "working":         {"input-required", "completed", "failed", "canceled"},
    "input-required":  {"working", "canceled", "failed"},
    "completed":       set(),
    "failed":          set(),
    "canceled":        set(),
    "rejected":        set(),
}


def apply_signed_artifact(local_state: str, artifact: dict, refetch_card) -> str:
    """Apply a signature-verified artifact. Returns the new local state.

    Signature verification is assumed to have happened upstream; this
    function enforces transition legality and Card re-fetch policy.
    """
    remote_state = artifact.get("taskState")
    if remote_state is None:
        raise UnmodeledTransitionError("artifact missing taskState field")

    if remote_state in LEGAL_EDGES.get(local_state, set()):
        return remote_state

    # Unmodeled edge. Re-fetch the Card once (bounded) to see if the
    # advertised graph changed since discovery.
    card = refetch_card()
    advertised = set(card.get("capabilities", {}).get("taskStates", []))

    if remote_state in advertised and remote_state in LEGAL_EDGES.get(local_state, set()):
        # Card was stale; adopt the newly advertised edge.
        return remote_state

    # Remote emitted a state we cannot legally reach from here, and the
    # refreshed Card does not legitimize it. Do NOT retry the refused
    # transition. Surface for human/agent escalation with full context.
    raise UnmodeledTransitionError(
        f"remote emitted taskState={remote_state!r} from local_state={local_state!r}; "
        f"advertised={sorted(advertised)}; refusing to retry refused transition"
    )
