# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-tool-output-s-provenance-chain-when-an-intermediate-agent-is-authorized-to-re-sign-and-what-breaks-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-tool-output-s-provenance-chain-when-an-intermediate-agent-is-authorized-to-re-sign-and-what-breaks-at-the.warrant.json
# Markdown SHA-256:   3545523cd0f5050c4dcd0858deb855eec805d14623db204708028744411341a8
# Code AST SHA-256:   98af614e8faf961018e8ffc6801d89165b84affa2fde5c4758163d25e0083166
# Verified Classes:   ProvenanceCoverageError, Authority, SignedRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ProvenanceCoverageError(RuntimeError):
    """Raised when a re-signed provenance link is cryptographically closed
    but does not cover the payload actually consumed by the next hop."""


class Authority(Enum):
    ORIGIN = "origin"            # tool / leaf agent: attests truth of output
    RECEIPT_FORWARD = "receipt"  # re-signer: attests only what it received
    SEMANTIC = "semantic"        # re-signer: attests the bytes it delivered


@dataclass(frozen=True)
class SignedRecord:
    signer: str
    authority: Authority
    signed_digest: str           # hash the signer committed to
    delivered_payload: bytes     # bytes actually handed to the next hop


def digest(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def audit_link(record: SignedRecord, require_semantic: bool) -> None:
    # Cryptographic closure: the signature itself is assumed valid here.
    # The failure we guard is *coverage*, not signature validity.
    actual = digest(record.delivered_payload)

    if record.signed_digest != actual:
        # Re-signer signed one thing, delivered another (truncation,
        # paraphrase, re-serialization). Chain closes; action escapes.
        raise ProvenanceCoverageError(
            f"coverage gap at signer={record.signer}: "
            f"signed={record.signed_digest[:12]} delivered={actual[:12]} "
            f"authority={record.authority.value}"
        )

    if require_semantic and record.authority is not Authority.SEMANTIC:
        # Authority laundering: a receipt/forward witness presented as if
        # it carried origin-equivalent evidentiary weight.
        raise ProvenanceCoverageError(
            f"authority laundering at signer={record.signer}: "
            f"chain requires semantic attestation, signer holds "
            f"{record.authority.value} only"
        )


def audit_chain(chain: list[SignedRecord]) -> None:
    # Cross >=2 re-signing hops => demand semantic authority at each.
    require_semantic = sum(
        1 for r in chain if r.authority is not Authority.ORIGIN
    ) >= 2
    for record in chain:
        audit_link(record, require_semantic=require_semantic)


# Triggering trace: A re-signs R_T correctly, then delivers a truncated
# payload to B. Signature verifies; coverage fails.
bad_chain = [
    SignedRecord("tool_T", Authority.ORIGIN, digest(b"full-db-row"), b"full-db-row"),
    SignedRecord("agent_A", Authority.RECEIPT_FORWARD,
                 digest(b"full-db-row"), b"full-db-row..."),  # truncated delivery
]
audit_chain(bad_chain)  # raises ProvenanceCoverageError
