# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-boundary-has-been-silently-inverted-by-policy-exchange-ordering.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-boundary-has-been-silently-inverted-by-policy-exchange-ordering.warrant.json
# Markdown SHA-256:   c804431816c149b6d40d6ae64f5ab1dec171512d4334768e7e76e5d7b8dcc548
# Code AST SHA-256:   695de7029ebab327fbfda1104d18029a0b598a4ea79e3214fbbfaf9cfac5e8a6
# Verified Classes:   TrustEdgeInversionError, PolicyBundle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TrustEdgeInversionError(RuntimeError):
    """Raised when a policy bundle would invert a federation trust edge."""
    pass


@dataclass(frozen=True)
class PolicyBundle:
    subject: str
    target: str
    scope: str
    grantor: Optional[str] = None
    grantee: Optional[str] = None


def resolve_edge(bundle: PolicyBundle, trusted_peers: frozenset[str]) -> tuple[str, str]:
    """Resolve the directed trust edge for a bundle.

    Direction must come from signed grantor/grantee fields. If absent, we
    refuse to infer from content heuristics (the root cause of silent
    inversion) and fail closed.
    """
    if bundle.grantor is None or bundle.grantee is None:
        raise TrustEdgeInversionError(
            f"bundle from {bundle.subject!r} lacks signed grantor/grantee; "
            f"refusing heuristic direction inference"
        )
    if bundle.grantor not in trusted_peers:
        raise TrustEdgeInversionError(
            f"bundle grantor {bundle.grantor!r} is not a trusted peer; "
            f"would create an unbacked edge into {bundle.grantee!r}"
        )
    if bundle.grantor == bundle.grantee:
        raise TrustEdgeInversionError(
            f"self-loop edge on {bundle.grantor!r} indicates malformed bundle"
        )
    return bundle.grantor, bundle.grantee


def apply_bundles(
    bundles: list[PolicyBundle], trusted_peers: frozenset[str]
) -> set[tuple[str, str]]:
    edges: set[tuple[str, str]] = set()
    for b in bundles:
        edges.add(resolve_edge(b, trusted_peers))
    return edges


if __name__ == "__main__":
    peers = frozenset({"orgA", "orgB"})
    # C's request-template bundle, misread as a grant, would invert B<->C.
    bad = PolicyBundle(subject="orgC", target="orgB", scope="read", grantor=None, grantee=None)
    try:
        apply_bundles([bad], peers)
    except TrustEdgeInversionError as e:
        print(f"rejected: {e}")
