# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-across-an-org-boundary-and-the-receipt-s-provenance-chain-diverges-from-the-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-across-an-org-boundary-and-the-receipt-s-provenance-chain-diverges-from-the-warrant-chain.warrant.json
# Markdown SHA-256:   92ca2798e9833866e84c8e68a4784636cac0713bbc7e81277333dafde199e639
# Code AST SHA-256:   5ecad4efa815de1ae68013976ab5cfbdf39053c1f5b26e426904c2c7cfbf1d07
# Verified Classes:   WarrantChainDivergence, Receipt, WarrantDAG
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantChainDivergence(RuntimeError):
    """Raised when a receipt's cited parent set does not exactly equal the
    warrant set that authorized the action, indicating a linearized fan-out
    or an authority-widening divergence across an org boundary."""
    pass


@dataclass(frozen=True)
class Receipt:
    receipt_id: str
    action: str
    parents: FrozenSet[str]  # warrant hashes, NOT receipt hashes
    signer: str


@dataclass
class WarrantDAG:
    # warrant_hash -> set of parent warrant hashes (roots map to empty set)
    edges: dict = field(default_factory=dict)
    scopes: dict = field(default_factory=dict)

    def authorizing_set(self, action: str) -> FrozenSet[str]:
        # In a real system this walks the DAG and returns the exact set of
        # warrants whose scopes jointly subsume the action.
        return frozenset(self.scopes.keys())


def verify_receipt_against_warrants(
    receipt: Receipt, dag: WarrantDAG, action: str
) -> None:
    if not receipt.parents:
        raise WarrantChainDivergence(
            f"receipt {receipt.receipt_id} carries no parent warrant set; "
            f"cannot establish authority for action {action!r}"
        )

    expected = dag.authorizing_set(action)

    # The critical check: exact set equality, not membership, not topology.
    # A scalar parent that linearized a fan-out will fail here because the
    # receipt will cite one warrant while the DAG authorizes via several.
    if receipt.parents != expected:
        raise WarrantChainDivergence(
            f"receipt {receipt.receipt_id} for action {action!r} cites "
            f"parents {sorted(receipt.parents)} but warrant DAG authorizes "
            f"via {sorted(expected)}; likely a linearized fan-out across an "
            f"org boundary — refusing to treat receipt as proof of authority"
        )


def cross_org_handoff(receipt: Receipt, dag: WarrantDAG, action: str) -> str:
    verify_receipt_against_warrants(receipt, dag, action)
    return f"handoff accepted for {receipt.receipt_id}"
