# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-shadowed-capability-grant-when-federation-relay-strips-jurisdiction-tags-from-mcp-tool-descriptors.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-shadowed-capability-grant-when-federation-relay-strips-jurisdiction-tags-from-mcp-tool-descriptors.warrant.json
# Markdown SHA-256:   1f9234b4634aaca6501c6723d2f0d08681b4c6db909bb82e685e2aa1fd9c85b1
# Code AST SHA-256:   574b34d5c46cda56ac33283dcd58475c0188a7bbe13f8269ab82ce90cb15ed7f
# Verified Classes:   ConstraintStripDetected, UnverifiableFederatedGrant, GrantDescriptor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ConstraintStripDetected(RuntimeError):
    """Raised when a federated grant's received constraints do not match the issuer's digest."""


class UnverifiableFederatedGrant(RuntimeError):
    """Raised when a federated grant carries no digest and cannot be constrain-verified."""


@dataclass(frozen=True)
class GrantDescriptor:
    grant_id: str
    issuer_org: str
    receiver_org: str
    constraints: dict
    constraint_digest: bytes | None


def compute_digest(constraints: dict) -> bytes:
    canonical = json.dumps(constraints, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(canonical).hexdigest().encode()


def known_issuer_jurisdictions(issuer_org: str) -> list[str]:
    # In production this is a registry lookup, not a constant.
    return ["EU"]


def accept_grant(desc: GrantDescriptor) -> dict:
    federated = desc.issuer_org != desc.receiver_org

    if desc.constraint_digest is not None:
        expected = compute_digest(desc.constraints)
        if expected != desc.constraint_digest:
            raise ConstraintStripDetected(
                f"grant {desc.grant_id}: received constraints hash to {expected!r}, "
                f"issuer digest is {desc.constraint_digest!r}; a relay stripped fields"
            )
        return desc.constraints

    if federated:
        # No digest across an org boundary: cannot prove non-strip.
        # Fall back to the restrictive intersection, never to unconstrained.
        jurisdictions = known_issuer_jurisdictions(desc.issuer_org)
        if not jurisdictions:
            raise UnverifiableFederatedGrant(
                f"grant {desc.grant_id}: federated, no digest, issuer jurisdiction unknown"
            )
        return {"residency": jurisdictions[0], "_verified": False}

    return desc.constraints


def handle_relayed_descriptor(raw: dict) -> dict:
    desc = GrantDescriptor(
        grant_id=raw["grant_id"],
        issuer_org=raw["issuer_org"],
        receiver_org=raw["receiver_org"],
        constraints=raw.get("constraints", {}),
        constraint_digest=raw.get("constraint_digest"),
    )
    return accept_grant(desc)


if __name__ == "__main__":
    # Relay stripped constraints but the opaque digest survived.
    stripped = {
        "grant_id": "g-4417",
        "issuer_org": "org-b",
        "receiver_org": "org-a",
        "constraints": {},
        "constraint_digest": compute_digest({"residency": "EU", "data_classes": ["pii"]}),
    }
    handle_relayed_descriptor(stripped)  # raises ConstraintStripDetected
