# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-whose-signature-validates-but-whose-provenance-chain-was-severed-at-re-signing.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-whose-signature-validates-but-whose-provenance-chain-was-severed-at-re-signing.warrant.json
# Markdown SHA-256:   52f53fa4679a293dee1beae7622b19a706782cc71d4e8f12f81780a6df3c8c88
# Code AST SHA-256:   0ebf927f8c4b7821d0a4d4dbfba4805a6d0380d20be2adf0fc5af9d42c9fdab6
# Verified Classes:   ProvenanceChainSeveredError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ProvenanceChainSeveredError(RuntimeError):
    """Raised when a skill's leaf signature validates but the chain to the
    authoring identity cannot be reconstructed or has been re-signed away."""
    pass


def verify_skill(envelope: dict, authoring_key: bytes, allowlist: set[str]) -> str:
    # envelope: {"bytes", "leaf_sig", "leaf_key", "publisher", "chain": [...]}
    if not _leaf_signature_valid(envelope["bytes"], envelope["leaf_sig"], envelope["leaf_key"]):
        raise ProvenanceChainSeveredError("leaf signature invalid; reject outright")

    chain = envelope.get("chain") or []
    if not chain:
        # valid leaf, no chain: the re-signer is the sole attestor
        raise ProvenanceChainSeveredError(
            f"leaf valid but chain empty; publisher={envelope.get('publisher')!r} "
            "is a payload string, not a signed claim"
        )

    # walk from leaf back to author, re-checking each transformation
    current = envelope["bytes"]
    for hop in reversed(chain):
        if _hash(current) != hop["input_hash"]:
            raise ProvenanceChainSeveredError(
                f"hop {hop['signer']} input_hash mismatch: transformation unrecorded"
            )
        if not _leaf_signature_valid(current, hop["sig"], hop["key"]):
            raise ProvenanceChainSeveredError(f"hop {hop['signer']} signature invalid")
        current = hop["prior_bytes"]

    author_key = chain[0]["key"]
    if author_key != authoring_key:
        raise ProvenanceChainSeveredError("chain root is not the pinned authoring key")
    if envelope["publisher"] not in allowlist:
        raise ProvenanceChainSeveredError("publisher not allowlisted")
    if _is_revoked(author_key):
        raise ProvenanceChainSeveredError("authoring key revoked at load time")
    return "verified-and-attributed"
