# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-brokered-a2a-trust-warrant-s-delegated-scope-silently-narrows-across-a-federation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-brokered-a2a-trust-warrant-s-delegated-scope-silently-narrows-across-a-federation-hop.warrant.json
# Markdown SHA-256:   58b80ffcf78f473d9b8c3e7b12425d4f2f95767163b3101aca24576b2d7169ff
# Code AST SHA-256:   7b281fb45c280a010950f8e245e96794b4d80bfe8440309ff739c4d57406cffc
# Verified Classes:   ScopeDivergenceError, Warrant
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeDivergenceError(RuntimeError):
    """Raised when an arriving brokered warrant confers less authority than the
    origin delegated, with no origin-signed acknowledgment of the reduction."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    effective_scope: FrozenSet[str]
    parent_hash: str | None
    reduction_ack: FrozenSet[str] = field(default_factory=frozenset)
    reduction_ack_signed_by: str | None = None


def reconcile_arriving_warrant(
    arriving: Warrant,
    root: Warrant,
    origin_domain: str,
) -> None:
    """Enforce the federation scope-reconciliation invariant at acceptance time.

    Halts before task acceptance if the arriving warrant is a strict subset of
    the origin's delegated scope and the reduction is not origin-acknowledged.
    """
    if arriving.parent_hash is None:
        # Root warrant: nothing to reconcile against.
        return

    delegated = root.effective_scope
    effective = arriving.effective_scope
    reduction = delegated - effective

    if not reduction:
        return  # full authority preserved across the hop

    ack_covers_reduction = (
        arriving.reduction_ack_signed_by == origin_domain
        and reduction.issubset(arriving.reduction_ack)
    )
    if not ack_covers_reduction:
        raise ScopeDivergenceError(
            f"Broker {arriving.issuer!r} narrowed scope by {sorted(reduction)} "
            f"without origin-signed reduction_ack from {origin_domain!r}. "
            f"Refusing acceptance; origin state must not commit."
        )
    # Reduction explicitly negotiated: safe to accept with reduced authority.
