# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-capability-downgrade-it-never-negotiated-the-trust-broker-substitution-gap-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-capability-downgrade-it-never-negotiated-the-trust-broker-substitution-gap-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   7210a9758855abe34ab9cd17b6ca310147983a1890e941c87e2a5d6ba6f03b0b
# Code AST SHA-256:   86954118074971b06136dcd128a7e46234ade4a65353cae0a8daa00f28f3a890
# Verified Classes:   CapabilitySubstitutionError, NegotiatedTranscript, BrokerWarrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CapabilitySubstitutionError(RuntimeError):
    """Raised when a broker warrant's capability set diverges from the
    peer-negotiated transcript without an understood narrowing reason."""
    pass


@dataclass
class NegotiatedTranscript:
    peer_id: str
    capabilities: frozenset[str]
    transcript_hash: str


@dataclass
class BrokerWarrant:
    issuer: str
    capabilities: frozenset[str]
    narrowed: bool
    narrowing_reason: str | None
    signature_valid: bool
    metadata: dict = field(default_factory=dict)


# Narrowing reasons the requester's planner is prepared to handle as
# terminal-escalation events rather than routing-around constraints.
UNDERSTOOD_NARROWING_REASONS = frozenset({
    "jurisdiction_filter",
    "requester_local_policy_revocation",
})


def reconcile_warrant(
    transcript: NegotiatedTranscript,
    warrant: BrokerWarrant,
) -> frozenset[str]:
    """Return the effective capability set, or raise if the warrant
    silently substitutes a reduced set for the negotiated one."""

    if not warrant.signature_valid:
        raise CapabilitySubstitutionError(
            f"warrant from {warrant.issuer} failed signature verification"
        )

    # Invariant: broker may narrow but never widen beyond the negotiation.
    widened = warrant.capabilities - transcript.capabilities
    if widened:
        raise CapabilitySubstitutionError(
            f"broker widened beyond negotiation: {sorted(widened)}"
        )

    delta = transcript.capabilities - warrant.capabilities
    if not delta:
        return warrant.capabilities

    # A non-empty delta is only acceptable if the broker explicitly
    # flagged narrowing AND the reason is one the planner can escalate on.
    if not warrant.narrowed:
        raise CapabilitySubstitutionError(
            f"silent substitution: broker dropped {sorted(delta)} "
            f"without narrowing flag; transcript={transcript.transcript_hash}"
        )

    if warrant.narrowing_reason not in UNDERSTOOD_NARROWING_REASONS:
        raise CapabilitySubstitutionError(
            f"unhandled narrowing reason {warrant.narrowing_reason!r} "
            f"for dropped capabilities {sorted(delta)}; "
            f"refusing to initialize reduced tool surface"
        )

    # Narrowing is understood: planner must treat dropped caps as
    # terminal-escalation, not routing-around opportunities.
    return warrant.capabilities
