# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-a2a-peer-s-credential-whose-issuer-chain-verifies-but-whose-delegation-scope-silently-widens-at-the-trust-anch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-a2a-peer-s-credential-whose-issuer-chain-verifies-but-whose-delegation-scope-silently-widens-at-the-trust-anch.warrant.json
# Markdown SHA-256:   f2daa861e7b24c1fae82e653b36885c5567b6db634597a778efc3009148f21d9
# Code AST SHA-256:   6e4cc0260e372984a612a17523470a1412ea1c887113f4df0c726db73a43f024
# Verified Classes:   UnverifiableDelegationChainError, FederatedCredential, AnchorPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnverifiableDelegationChainError(RuntimeError):
    """Raised when a federated A2A credential's delegation chain cannot be
    reconciled against the relying party's trust anchor. Fail-closed: the
    handoff is refused and the task quarantined."""
    pass


@dataclass(frozen=True)
class FederatedCredential:
    subject: str
    issuer: str
    scope: frozenset[str]
    parent_scope_hash: str          # commitment over parent's scope set
    depth_remaining: int            # hops left before anchor


@dataclass(frozen=True)
class AnchorPolicy:
    anchor_id: str
    max_delegation_depth: int
    permitted_actions: frozenset[str]
    known_scope_hashes: frozenset[str]  # committed ancestor scopes seen for this peer


def scope_commitment(scope: frozenset[str]) -> str:
    canonical = "|".join(sorted(scope))
    return hashlib.sha256(canonical.encode()).hexdigest()


def verify_federated_credential(
    cred: FederatedCredential,
    anchor: AnchorPolicy,
) -> None:
    # Leaf scope must be within the anchor's permitted action set.
    if not cred.scope.issubset(anchor.permitted_actions):
        raise UnverifiableDelegationChainError(
            f"leaf scope {sorted(cred.scope)} exceeds anchor "
            f"{anchor.anchor_id} permitted {sorted(anchor.permitted_actions)}"
        )

    # Depth bound: a depth-2+ credential MUST carry a reconcilable commitment.
    if cred.depth_remaining > anchor.max_delegation_depth:
        raise UnverifiableDelegationChainError(
            f"depth_remaining {cred.depth_remaining} exceeds anchor bound "
            f"{anchor.max_delegation_depth}"
        )

    # The critical guardrail: if this credential is not a direct child of the
    # anchor, its parent scope commitment must be one the relying party has
    # already reconciled. An unknown commitment means an intermediate widened
    # (or forged) scope we cannot intersect against -- refuse.
    is_direct_child = cred.depth_remaining == anchor.max_delegation_depth - 1
    if not is_direct_child and cred.parent_scope_hash not in anchor.known_scope_hashes:
        raise UnverifiableDelegationChainError(
            f"unreconciled parent_scope_hash {cred.parent_scope_hash[:12]}... "
            f"for subject {cred.subject}; possible scope widening at "
            f"intermediate hop under anchor {anchor.anchor_id}"
        )


def admit_a2a_handoff(cred: FederatedCredential, anchor: AnchorPolicy) -> str:
    try:
        verify_federated_credential(cred, anchor)
    except UnverifiableDelegationChainError:
        # Quarantine, do not silently drop: emit to federation audit sink.
        return f"QUARANTINED:{cred.subject}"
    return f"ADMITTED:{cred.subject}"
