# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-warrant-scope-laundering-during-cross-org-a2a-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-warrant-scope-laundering-during-cross-org-a2a-capability-negotiation.warrant.json
# Markdown SHA-256:   699b69ebeacaa1047f5216d2c806c5d41924d90f0155541fe67e7f7f5b9fd299
# Code AST SHA-256:   56afc156f7ae1a099dda4c76a865c4440bad5a1f1cefa7a0778d9b316957b5a0
# Verified Classes:   LiabilityScopeDegraded, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LiabilityScopeDegraded(RuntimeError):
    """Raised when a re-issued warrant narrows liability scope relative to its parent."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    capability: frozenset
    liability_scope: frozenset  # set of action-classes the issuer will absorb
    parent: Optional["Warrant"] = None


def validate_federated_warrant(terminal: Warrant) -> None:
    """
    Walk the warrant chain and enforce both invariants:
      - capability is downward-closed across hops
      - liability_scope is upward-closed across hops
    Raises LiabilityScopeDegraded on any violation of the liability invariant.
    """
    hop = terminal
    while hop.parent is not None:
        parent = hop.parent

        # Capability must not widen.
        if not hop.capability.issubset(parent.capability):
            raise LiabilityScopeDegraded(
                f"capability widened at hop {hop.issuer}: "
                f"{hop.capability - parent.capability} not granted by {parent.issuer}"
            )

        # Liability must not narrow. This is the invariant that fails silently.
        missing = parent.liability_scope - hop.liability_scope
        if missing:
            raise LiabilityScopeDegraded(
                f"liability scope laundered at hop {hop.issuer}: "
                f"parent {parent.issuer} absorbed {sorted(parent.liability_scope)}, "
                f"re-issuer dropped {sorted(missing)}; "
                f"no accountable party for {sorted(hop.capability & missing)}"
            )

        hop = parent


def accept_handoff(terminal: Warrant, local_underwriter_capacity: frozenset) -> bool:
    """
    Accept a federated handoff only if the chain is liability-sound, or if the
    local instance explicitly assumes the residual liability and records it.
    """
    try:
        validate_federated_warrant(terminal)
        return True
    except LiabilityScopeDegraded as e:
        residual = terminal.capability  # actions we would be executing
        if residual.issubset(local_underwriter_capacity):
            # We can absorb it ourselves; record the assumption, do not launder further.
            _record_liability_assumption(terminal, residual, reason=str(e))
            return True
        raise LiabilityScopeDegraded(
            f"refusing handoff: {e}; local capacity {sorted(local_underwriter_capacity)} "
            f"cannot absorb {sorted(residual)}"
        ) from e


def _record_liability_assumption(warrant: Warrant, scope: frozenset, reason: str) -> None:
    # Append to the immutable audit log; this is the only legal way to accept
    # a degraded warrant, and it makes the assuming party the liable party.
    ...
