# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-taint-survive-tool-re-instantiation-but-not-agent-handoff-the-sandbox-provenance-split-in-untrusted-content-ingestion.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-taint-survive-tool-re-instantiation-but-not-agent-handoff-the-sandbox-provenance-split-in-untrusted-content-ingestion.warrant.json
# Markdown SHA-256:   4c3e24d611281c1bcc99cdb04407add5fae836e86d818307f14fb1e92f0684c2
# Code AST SHA-256:   c0b7961d8b661946a3872e58321e84328d08490a25889b67b95b434789aeb909
# Verified Classes:   TaintProvenanceSplitError, LeaseToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class TaintProvenanceSplitError(RuntimeError):
    """Raised when payload taint label and tool capability profile disagree at lease time."""
    pass


@dataclass(frozen=True)
class LeaseToken:
    payload_hash: str
    taint_label: Optional[str]
    capability_profile: str
    requires_taint_restriction: bool


def validate_lease(token: LeaseToken) -> None:
    tainted = token.taint_label is not None
    if tainted and not token.requires_taint_restriction:
        raise TaintProvenanceSplitError(
            f"payload {token.payload_hash[:12]} is tainted ({token.taint_label}) "
            f"but leased tool profile '{token.capability_profile}' does not enforce restriction"
        )
    if not tainted and token.requires_taint_restriction:
        raise TaintProvenanceSplitError(
            f"payload {token.payload_hash[:12]} is unlabeled but leased tool profile "
            f"'{token.capability_profile}' expects a taint label; label was likely dropped in handoff"
        )


def lease_tool(payload: bytes, taint_label: Optional[str], profile: str,
               profile_requires_restriction: bool) -> LeaseToken:
    token = LeaseToken(
        payload_hash=hashlib.sha256(payload).hexdigest(),
        taint_label=taint_label,
        capability_profile=profile,
        requires_taint_restriction=profile_requires_restriction,
    )
    validate_lease(token)
    return token
