# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-data-sovereignty-clause-it-cannot-evaluate-at-handshake-time.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-data-sovereignty-clause-it-cannot-evaluate-at-handshake-time.warrant.json
# Markdown SHA-256:   0657865b470d9a7725c4a61535238a0054c6da2934e39b4b22e06482b5388185
# Code AST SHA-256:   f6c14b8a537502cc6b4729bbf381b663a2b80a53eb67faad5cd9034c9aaa63cb
# Verified Classes:   SovereigntyPreflightError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SovereigntyPreflightError(RuntimeError):
    """Raised when a federated grant carries a sovereignty predicate the
    consumer cannot decide locally and no pre-flight attestation channel
    was advertised by the provider. Fails closed before payload emission."""
    pass


OPAQUE_PREDICATE_KINDS = frozenset({
    "processing_region",
    "no_cross_border_derivation",
    "derived_work_retention",
})


def activate_grant(grant: dict, provider_manifest_endpoint: str | None) -> str:
    """Decide whether a negotiated grant may become ACTIVE for the consumer.

    Invariant: a grant with any opaque sovereignty predicate is executable
    only if the provider exposes a pre-flight attestation endpoint. Otherwise
    we must refuse activation rather than default to satisfied-by-signature.
    """
    predicates = grant.get("sovereignty", {})
    opaque = [k for k in predicates if k in OPAQUE_PREDICATE_KINDS]

    if opaque and not provider_manifest_endpoint:
        raise SovereigntyPreflightError(
            f"grant {grant.get('id')!r} carries undecidable sovereignty "
            f"predicates {opaque} with no pre-flight attestation channel; "
            f"refusing ACTIVE transition to prevent pre-decision data egress"
        )

    if opaque and provider_manifest_endpoint:
        # Caller must submit a payload manifest (residency tags, derivation
        # flags, volume) to the endpoint and receive an explicit ALLOW before
        # any payload bytes are serialized for transport.
        return "PENDING_ATTESTATION"

    return "ACTIVE"


def handle_tool_error(grant_id: str, error_code: str) -> str:
    """Classify tool errors. Policy outcomes are terminal, never retried."""
    if error_code == "SOVEREIGNTY_VIOLATION":
        # Do not re-emit the payload; the boundary was already approached.
        raise SovereigntyPreflightError(
            f"grant {grant_id!r} hit SOVEREIGNTY_VIOLATION at execution; "
            f"payload must not be retried — predicate was opaque at handshake"
        )
    return "RETRYABLE"
