# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-warrant-when-the-negotiated-scope-is-a-strict-superset-of-the-local-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-warrant-when-the-negotiated-scope-is-a-strict-superset-of-the-local-capability.warrant.json
# Markdown SHA-256:   3d3081e0372397ba018c638f2b376ec08807a429694212cdb1d7d232db429792
# Code AST SHA-256:   7129114860d804efc2feb199796c64e1c2a37875d340dd5a63835b4319d6b0ad
# Verified Classes:   FederatedWarrantError, CapabilityManifest, PolicyWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class FederatedWarrantError(RuntimeError):
    """Raised when a federated policy warrant violates the subset invariant."""
    pass


@dataclass(frozen=True)
class CapabilityManifest:
    authorities: FrozenSet[str]
    version: int


@dataclass(frozen=True)
class PolicyWarrant:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    chain: tuple = field(default_factory=tuple)  # resolved upstream warrants
    signature_valid: bool = True


def effective_scope(warrant: PolicyWarrant) -> FrozenSet[str]:
    """Resolve the transitive closure of a warrant's delegated scope."""
    scope = set(warrant.scope)
    for upstream in warrant.chain:
        scope |= upstream.scope
    return frozenset(scope)


def accept_federated_warrant(
    local: CapabilityManifest,
    warrant: PolicyWarrant,
    manifest_is_fresh: bool,
) -> FrozenSet[str]:
    """
    Enforce the subset invariant. Returns the scope to record on the trust
    edge (always the intersection). Raises on any condition of invalidity.
    """
    if not warrant.signature_valid:
        raise FederatedWarrantError(
            f"warrant from {warrant.issuer} failed signature validation"
        )

    if not manifest_is_fresh:
        # Stale manifest: cannot prove subset against current authorities.
        raise FederatedWarrantError(
            f"cannot evaluate warrant from {warrant.issuer}: "
            f"local manifest v{local.version} is stale"
        )

    resolved = effective_scope(warrant)
    excess = resolved - local.authorities

    if excess:
        # Superset scope: refuse, do not silently narrow.
        raise FederatedWarrantError(
            f"warrant from {warrant.issuer} scopes {sorted(excess)} "
            f"which exceed local manifest v{local.version}; "
            f"renegotiation required, acceptance refused"
        )

    # Subset or equal: record the edge at the resolved intersection.
    return resolved & local.authorities


def record_trust_edge(edge_table: dict, peer: str, scope: FrozenSet[str]) -> None:
    if peer in edge_table and not scope <= edge_table[peer]:
        raise FederatedWarrantError(
            f"edge to {peer} would widen from {sorted(edge_table[peer])} "
            f"to {sorted(scope)}; widening edges are forbidden"
        )
    edge_table[peer] = scope
