# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-authority-widening-in-a2a-v1-0-multi-hop-signed-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-authority-widening-in-a2a-v1-0-multi-hop-signed-task-delegation.warrant.json
# Markdown SHA-256:   b018c4aeb38f384ae7c9701ee5e6fcc8d9b86fb3d933be877a43d1cb1c6d1895
# Code AST SHA-256:   c125ef717f20dfa6160f6b7c478949e66cf8538283e8ce3f7715abc38cbcb4b6
# Verified Classes:   DelegationUnprovable, Grant, Envelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class DelegationUnprovable(RuntimeError):
    """Raised when a hop cannot prove the intersection of signed grants."""


@dataclass(frozen=True)
class Grant:
    capability: str  # e.g. "fs:read:/data", "net:egress:internal"


@dataclass(frozen=True)
class Envelope:
    issuer: str
    chain: tuple[Grant, ...]  # ordered grants from originator through this hop
    card_digests: tuple[str, ...]  # digest of each hop's Agent Card at signing time
    algorithm_version: str


REQUIRED_ALGORITHM = "intersect-v1"


def resolve_effective_scope(
    envelope: Envelope,
    child_card_capabilities: Iterable[str],
    supported_algorithms: Iterable[str] = (REQUIRED_ALGORITHM,),
) -> frozenset[str]:
    """Compute the effective authority for a delegated task.

    Effective scope is the intersection of every signed grant in the chain.
    Agent Card capabilities are used ONLY to reject impossible requests;
    they never contribute to the effective scope.
    """
    if not envelope.chain:
        raise DelegationUnprovable(
            f"envelope from {envelope.issuer!r} carries no grant chain; "
            "cannot distinguish advertised capability from signed grant"
        )
    if len(envelope.card_digests) != len(envelope.chain):
        raise DelegationUnprovable(
            f"envelope from {envelope.issuer!r} has {len(envelope.chain)} grants "
            f"but {len(envelope.card_digests)} card digests; derivation is not reproducible"
        )
    if envelope.algorithm_version not in set(supported_algorithms):
        raise DelegationUnprovable(
            f"envelope from {envelope.issuer!r} signed under algorithm "
            f"{envelope.algorithm_version!r}, which this hop does not implement; "
            "refusing to fall back to parent grant alone"
        )

    effective: set[str] = {g.capability for g in envelope.chain[0]}
    for grant_set in envelope.chain[1:]:
        effective &= {g.capability for g in grant_set}

    # Card capabilities may only veto, never widen.
    child_card = set(child_card_capabilities)
    impossible = effective - child_card
    if impossible:
        raise DelegationUnprovable(
            f"child advertises no support for {sorted(impossible)!r}; "
            "signed grant cannot be honored, refusing delegation"
        )

    return frozenset(effective)


def negotiate_handoff(
    parent_envelope: Envelope,
    child_card_capabilities: Iterable[str],
    child_grant: Iterable[Grant],
) -> Envelope:
    """Build the child envelope, propagating the full chain."""
    scope = resolve_effective_scope(parent_envelope, child_card_capabilities)
    # The child may be granted strictly less than the parent holds, never more.
    proposed = {g.capability for g in child_grant}
    if not proposed <= scope:
        raise DelegationUnprovable(
            f"proposed child grant {sorted(proposed - scope)!r} exceeds "
            f"effective parent scope {sorted(scope)!r}"
        )
    return Envelope(
        issuer="child",
        chain=parent_envelope.chain + (tuple(child_grant),),
        card_digests=parent_envelope.card_digests + ("<digest-of-child-card>",),
        algorithm_version=REQUIRED_ALGORITHM,
    )
