# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-attestation-chain-when-the-trust-anchor-is-a-self-signed-root.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-peer-s-attestation-chain-when-the-trust-anchor-is-a-self-signed-root.warrant.json
# Markdown SHA-256:   d33869e8a0fcf838731fe2d1c93730210d2439e702d079c98ef505667c968f28
# Code AST SHA-256:   f446915722152a93210dfe05b2ccc08efc487dde1c656d9ce40f5b936423bc0f
# Verified Classes:   AttestationTrustError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttestationTrustError(RuntimeError):
    """Raised when a peer attestation chain cannot ground delegated authority."""
    pass


def verify_delegation(chain, envelope, pinned_roots, principal_scopes):
    # Anchor condition: chain must terminate at a pinned root.
    if chain.root not in pinned_roots:
        raise AttestationTrustError(
            f"unpinned root {chain.root!r}; refusing trust-on-first-use for agent identity"
        )

    # Binding condition: leaf must name a delegating principal we recognize.
    bound = chain.leaf.bound_principal
    if bound is None or bound not in principal_scopes:
        raise AttestationTrustError(
            f"chain valid under pinned root but leaf does not bind a known principal "
            f"(claimed={bound!r}); chain proves key possession, not authority"
        )

    # Scope condition: envelope scope must be a subset of the principal's real scope.
    authorized = principal_scopes[bound]
    if not set(envelope.scope).issubset(authorized):
        raise AttestationTrustError(
            f"envelope scope {sorted(envelope.scope)} exceeds principal {bound!r} "
            f"authorized scope {sorted(authorized)}"
        )

    return True
