# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-tasks-resubscribe-stream-reattach-when-the-remote-agent-card-s-statetransitionhistory-capabi.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-an-a2a-v1-0-tasks-resubscribe-stream-reattach-when-the-remote-agent-card-s-statetransitionhistory-capabi.warrant.json
# Markdown SHA-256:   d83db853ef5bf657ff572605d2973e7d16a63636c43a43af4215a080c43c1015
# Code AST SHA-256:   b3a50c30b3fefd39c9884e65ce5fd02765836707eb173733f5d99aa0e20142be
# Verified Classes:   CapabilityDowngradeOnResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityDowngradeOnResumeError(RuntimeError):
    """Raised when a task resume is attempted against a remote agent whose
    stateTransitionHistory capability was downgraded since dispatch, making
    gap-free history replay impossible."""
    pass


def gate_resubscribe(cached_card: dict, current_card: dict, mirror_last_ts: float,
                     authoritative_status: dict) -> str:
    # Identity must be stable across the resume.
    if (cached_card.get("name"), cached_card.get("version")) != (
        current_card.get("name"), current_card.get("version")
    ):
        raise CapabilityDowngradeOnResumeError(
            "AgentCard identity changed between dispatch and resume; "
            "taskId semantics invalidated, abort and re-dispatch."
        )

    cached_hist = bool(cached_card.get("capabilities", {}).get("stateTransitionHistory"))
    current_hist = bool(current_card.get("capabilities", {}).get("stateTransitionHistory"))
    current_stream = bool(current_card.get("capabilities", {}).get("streaming"))

    if not current_stream:
        raise CapabilityDowngradeOnResumeError(
            "streaming capability absent on current card; cannot reattach."
        )

    if cached_hist and not current_hist:
        # Downgrade detected: refuse the stream, force snapshot reconciliation.
        server_ts = float(authoritative_status.get("timestamp", 0.0))
        if server_ts <= mirror_last_ts:
            raise CapabilityDowngradeOnResumeError(
                "Mirror timestamp not a strict prefix of server state after "
                "history downgrade; divergence requires escalation."
            )
        return "RECONCILE_SNAPSHOT"

    if not current_hist:
        raise CapabilityDowngradeOnResumeError(
            "stateTransitionHistory never available and no snapshot path; "
            "cannot guarantee prefix monotonicity."
        )

    return "RESUBSCRIBE"
