# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-discover-capability-scope-only-after-federation-handshake-completes-the-post-negotiation-privilege-widening-trap-in-cross-org-a2a.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-discover-capability-scope-only-after-federation-handshake-completes-the-post-negotiation-privilege-widening-trap-in-cross-org-a2a.warrant.json
# Markdown SHA-256:   eb44cceb65576e49ae8a2b82b152c1f25830cbdaf78548d380ce273f76c1c3a4
# Code AST SHA-256:   aae682e82b331af5bf05e616c8345b99384170f1b1cedac33037169efec1dfb4
# Verified Classes:   ScopeNegotiationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeNegotiationError(RuntimeError):
    """Raised when a remote manifest cannot be reconciled to a valid local grant."""
    pass


def negotiate_session_scope(remote_manifest: set[str],
                            local_allowlist: set[str],
                            policy_version: str,
                            manifest_cache: dict) -> dict:
    # Cache key MUST include policy version; a manifest is only valid
    # relative to the policy that will judge it.
    cache_key = (frozenset(remote_manifest), policy_version)
    if cache_key in manifest_cache:
        cached = manifest_cache[cache_key]
    else:
        cached = remote_manifest
        manifest_cache[cache_key] = cached

    # The remote manifest is a CLAIM, never a GRANT.
    # Effective scope is the intersection, not the union.
    effective = cached & local_allowlist

    if not effective:
        raise ScopeNegotiationError(
            f"manifest {sorted(cached)} disjoint from allowlist "
            f"{sorted(local_allowlist)} at policy {policy_version}"
        )

    # Enforce at mint time: the token must not carry any claim the
    # downstream guard would reject. Mint only after intersection.
    return {
        "granted": sorted(effective),
        "denied": sorted(cached - local_allowlist),
        "policy_version": policy_version,
    }


def mint_token(scope: dict) -> str:
    if not scope.get("granted"):
        raise ScopeNegotiationError("refusing to mint token with empty grant")
    # Downstream guard uses the same allowlist object evaluated here.
    return f"tok:{hash(tuple(scope['granted']))}"
