# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-the-delegated-principal-into-the-execution-receipt-or-the-attestation-chain-silently-re-roots.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-the-delegated-principal-into-the-execution-receipt-or-the-attestation-chain-silently-re-roots.warrant.json
# Markdown SHA-256:   01f0d7b5b8f7730676c9dc251a02f4c6f00281dd28be67d7360b102422cdf788
# Code AST SHA-256:   b136fb6b386f664e4ec58417c25c57378a5b29184ffc08c351f82ec472eace44
# Verified Classes:   DelegationAttestationError, Warrant, Receipt
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class DelegationAttestationError(RuntimeError):
    """Raised when a receipt cannot be verified as a delegation attestation."""
    pass


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: str
    max_delegation_depth: int
    depth: int
    prev_hash: Optional[str] = None

    def digest(self) -> str:
        pre = f"{self.issuer}|{self.subject}|{self.scope}|{self.max_delegation_depth}|{self.depth}|{self.prev_hash}"
        return hashlib.sha256(pre.encode()).hexdigest()


@dataclass
class Receipt:
    executor: str
    caller: str
    principal: Optional[str]
    tool: str
    args_hash: str
    output_hash: str
    chain: list = field(default_factory=list)  # ordered root -> leaf
    sig: Optional[str] = None


def verify_delegation_receipt(receipt: Receipt, trust_root: str, revoked: set) -> str:
    # 1. Chain completeness: a delegated receipt MUST carry its full chain.
    if not receipt.chain:
        raise DelegationAttestationError(
            f"receipt from {receipt.executor} has no warrant chain; "
            "cannot verify as delegation attestation (executor-only at best)"
        )

    # 2. Root binding: chain must terminate at the trust anchor.
    root = receipt.chain[0]
    if root.issuer != trust_root:
        raise DelegationAttestationError(
            f"chain root issuer {root.issuer!r} != trust root {trust_root!r}; "
            "attestation has re-rooted"
        )

    # 3. Principal binding: principal must equal root subject.
    if receipt.principal != root.subject:
        raise DelegationAttestationError(
            f"receipt principal {receipt.principal!r} != root subject {root.subject!r}; "
            "attribution would drift to caller"
        )

    # 4. Walk the chain: depth monotonicity, link integrity, revocation.
    prev = None
    for i, w in enumerate(receipt.chain):
        if w.depth != i:
            raise DelegationAttestationError(
                f"warrant depth {w.depth} at position {i}; chain is not monotonic"
            )
        if i > 0:
            parent = receipt.chain[i - 1]
            if w.max_delegation_depth > parent.max_delegation_depth:
                raise DelegationAttestationError(
                    f"warrant at depth {i} widens delegation beyond parent"
                )
            if w.depth > parent.max_delegation_depth:
                raise DelegationAttestationError(
                    f"delegation depth {w.depth} exceeds parent max "
                    f"{parent.max_delegation_depth} (constraint evaporation)"
                )
            if w.prev_hash != parent.digest():
                raise DelegationAttestationError(
                    f"warrant at depth {i} does not link to parent; chain broken"
                )
        if w.issuer in revoked or w.subject in revoked:
            raise DelegationAttestationError(
                f"warrant at depth {i} touches revoked identity; "
                "revocation must propagate to receipts"
            )
        prev = w

    # 5. Leaf binding: executor must equal leaf subject.
    leaf = receipt.chain[-1]
    if receipt.executor != leaf.subject:
        raise DelegationAttestationError(
            f"executor {receipt.executor!r} != leaf warrant subject {leaf.subject!r}"
        )

    # 6. Output attribution: digest must bind principal, not caller.
    expected = hashlib.sha256(
        f"{receipt.principal}|{receipt.tool}|{receipt.args_hash}|{receipt.output_hash}".encode()
    ).hexdigest()
    if receipt.sig != expected:
        raise DelegationAttestationError(
            "receipt signature does not bind principal into the output digest; "
            "outputs are fungible across principals"
        )

    return "VALID_DELEGATION"
