# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-bundle-as-unverified-despite-a-valid-signature-and-how-does-trust-bootstrap-divergence-cor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-bundle-as-unverified-despite-a-valid-signature-and-how-does-trust-bootstrap-divergence-cor.warrant.json
# Markdown SHA-256:   f5d40877e934a3090cdf97b76ae415a4a1c9bd301a39d2071589a67fea12cd5d
# Code AST SHA-256:   f37fa21a19447b6c7b01726abf5c167fdde273e376ac5e86c609ca7981651b06
# Verified Classes:   FederationTrustDivergence, Anchor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class FederationTrustDivergence(RuntimeError):
    """Raised when a signed policy bundle asserts claims beyond its bootstrapped anchor scope."""
    pass


class Anchor:
    def __init__(self, peer_org_id: str, source: str, public_key: str, claim_scope: frozenset):
        self.peer_org_id = peer_org_id
        self.source = source
        self.public_key = public_key
        self.claim_scope = claim_scope  # e.g. {"identity", "capability:refund.issue"}

    def cache_key(self):
        # Full tuple: distinct trust roots for the same org must never merge.
        return (self.peer_org_id, self.source, self.public_key)


def admit_policy_bundle(anchor: Anchor, bundle: dict, signature_valid: bool) -> dict:
    if not signature_valid:
        raise FederationTrustDivergence(
            f"bundle from {anchor.peer_org_id} failed integrity check; not admitted"
        )

    asserted = set(bundle.get("claims", []))
    beyond_scope = asserted - anchor.claim_scope
    if beyond_scope:
        # Signature is pristine, but the anchor was never bootstrapped to vouch for these.
        raise FederationTrustDivergence(
            f"bundle from {anchor.peer_org_id} via {anchor.source} asserts claims "
            f"outside bootstrapped scope {sorted(anchor.claim_scope)}: "
            f"{sorted(beyond_scope)}; quarantine and require explicit re-bootstrap"
        )

    return bundle  # admitted: integrity AND scope both satisfied


def load_peer_policy(anchor_cache: dict, peer_org_id: str, source: str,
                     public_key: str, bundle: dict, signature_valid: bool) -> dict:
    key = (peer_org_id, source, public_key)
    anchor = anchor_cache.get(key)
    if anchor is None:
        # First contact: bootstrap an identity-only anchor, never a capability anchor.
        anchor = Anchor(peer_org_id, source, public_key, frozenset({"identity"}))
        anchor_cache[key] = anchor
    return admit_policy_bundle(anchor, bundle, signature_valid)
