# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-a2a-v1-0-task-state-as-authoritative-over-its-own-agent-card-capabilities-when-a-cross-vendor-peer-reports-a-state-the-lo.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-a2a-v1-0-task-state-as-authoritative-over-its-own-agent-card-capabilities-when-a-cross-vendor-peer-reports-a-state-the-lo.warrant.json
# Markdown SHA-256:   7a6ec74c2ba757cb8061bc255a65083c92618b0269f70c19322ba1eae4899a80
# Code AST SHA-256:   c753a6d396b3c967a1c494e1f3b38b7c15de682e11a83425395b62ca0c46a15a
# Verified Classes:   CardStateWhitelistViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CardStateWhitelistViolation(RuntimeError):
    """Raised when a returned task state is absent from the card-derived set
    AND no capability extension has been observed on the task to justify it."""
    pass


CANONICAL_STATES = frozenset(
    {"submitted", "working", "input-required", "completed", "failed", "canceled"}
)


def validate_transition(
    returned_state: str,
    card_states: frozenset,
    task_extension_states: frozenset,
    extension_observed: bool,
) -> str:
    """Decide whether a returned state is legal for this task.

    Invariant: card_states is a lower bound, not a whitelist. A state outside
    card_states is legal iff an extension was observed on this task and the
    state is in task_extension_states (or the canonical vocabulary).
    """
    if returned_state not in CANONICAL_STATES:
        raise CardStateWhitelistViolation(
            f"state {returned_state!r} not in A2A canonical vocabulary"
        )

    if returned_state in card_states:
        return "card-legal"

    if not extension_observed:
        # No extension seen: the peer returned a state it never negotiated.
        raise CardStateWhitelistViolation(
            f"state {returned_state!r} outside card set {sorted(card_states)} "
            f"with no capability extension on task"
        )

    if returned_state in task_extension_states:
        return "extension-legal"

    # Extension observed but does not cover this state: protocol violation.
    raise CardStateWhitelistViolation(
        f"state {returned_state!r} outside card set and outside declared "
        f"extension states {sorted(task_extension_states)}"
    )


def apply_peer_update(
    task_id: str,
    update: dict,
    card_states: frozenset,
    prior_extension_states: frozenset,
) -> tuple[str, frozenset]:
    """Apply an inbound task update, rebuilding the legal state set if needed."""
    extension = update.get("metadata", {}).get("capabilityExtension")
    extension_observed = extension is not None or bool(prior_extension_states)

    if extension is not None:
        declared = frozenset(extension.get("declaredStates", []))
        task_extension_states = prior_extension_states | declared
    else:
        task_extension_states = prior_extension_states

    verdict = validate_transition(
        update["state"], card_states, task_extension_states, extension_observed
    )

    if verdict == "extension-legal" and update["state"] not in card_states:
        # Negotiation event, not an error. Log and continue.
        update.setdefault("_audit", []).append(
            f"negotiation:{task_id}:{update['state']}"
        )

    return update["state"], task_extension_states
