# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-jurisdictional-capability-leakage-when-a-federated-peer-silently-substitutes-a-same-named-tool-under-a-weaker-residency-po.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-jurisdictional-capability-leakage-when-a-federated-peer-silently-substitutes-a-same-named-tool-under-a-weaker-residency-po.warrant.json
# Markdown SHA-256:   a8a494662f52277df6325daa8be1b5d3c01541b8bffe1e4e45f96240bd6f8e07
# Code AST SHA-256:   be911b4e3fa77dcdade897273c23841fb2e9a4fa82c55f97d732fcb312672a02
# Verified Classes:   CapabilitySubstitutionError, JurisdictionViolationError, Expectation, Grant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilitySubstitutionError(RuntimeError):
    """Raised when a negotiated grant's identity tuple diverges from the caller's expectation."""
    pass


class JurisdictionViolationError(RuntimeError):
    """Raised when a grant's jurisdiction is outside the task's allowed set."""
    pass


@dataclass(frozen=True)
class Expectation:
    tool_id: str
    policy_digest: str
    allowed_jurisdictions: frozenset
    trusted_issuers: frozenset


@dataclass(frozen=True)
class Grant:
    tool_id: str
    policy_digest: str
    jurisdiction: str
    issuing_org: str
    grant_token: str  # peer-signed binding of the tuple above + task_id


def validate_grant(expectation: Expectation, grant: Grant, task_id: str) -> None:
    # Name check is necessary but NOT sufficient; the tuple is the identity.
    if grant.tool_id != expectation.tool_id:
        raise CapabilitySubstitutionError(
            f"tool_id mismatch: expected {expectation.tool_id!r}, got {grant.tool_id!r}"
        )
    if grant.policy_digest != expectation.policy_digest:
        raise CapabilitySubstitutionError(
            f"policy_digest mismatch for {grant.tool_id!r}: "
            f"expected {expectation.policy_digest}, got {grant.policy_digest} "
            f"(peer likely resolved name in a different residency shard)"
        )
    if grant.jurisdiction not in expectation.allowed_jurisdictions:
        raise JurisdictionViolationError(
            f"jurisdiction {grant.jurisdiction!r} not in allowed set "
            f"{sorted(expectation.allowed_jurisdictions)} for task {task_id}"
        )
    if grant.issuing_org not in expectation.trusted_issuers:
        raise CapabilitySubstitutionError(
            f"issuing_org {grant.issuing_org!r} not trusted for task {task_id}"
        )
    # Token must bind the same tuple; a token that omits any field is inadmissible.
    expected_token_material = (
        f"{task_id}|{grant.tool_id}|{grant.policy_digest}|"
        f"{grant.jurisdiction}|{grant.issuing_org}"
    )
    if not grant.grant_token or hashlib.sha256(
        expected_token_material.encode()
    ).hexdigest() not in grant.grant_token:
        raise CapabilitySubstitutionError(
            f"grant_token does not bind the full identity tuple for {grant.tool_id!r}"
        )


def negotiate_and_bind(expectations, peer_grants, task_id):
    by_name = {e.tool_id: e for e in expectations}
    for grant in peer_grants:
        exp = by_name.get(grant.tool_id)
        if exp is None:
            raise CapabilitySubstitutionError(
                f"peer granted unrequested capability {grant.tool_id!r}"
            )
        validate_grant(exp, grant, task_id)
    return {g.tool_id: g for g in peer_grants}
