# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-taint-label-after-tool-mediated-content-mutation-and-why-provenance-preserving-isolation-fails-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-taint-label-after-tool-mediated-content-mutation-and-why-provenance-preserving-isolation-fails-at-the.warrant.json
# Markdown SHA-256:   a6e7a94a677c5e8dbb1661f17fe5ae7231570479452da5cd0e36cd3fe2aa3c8f
# Code AST SHA-256:   5daf8e6d52aca9264eaaa3adf0258762d4f8f2ecb019feb07ac229e972d1fbe1
# Verified Classes:   TaintProvenanceError, TaintedValue, DeclassificationRecord, IsolationGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintProvenanceError(RuntimeError):
    """Raised when a taint label's referent no longer matches the content it guards."""


@dataclass
class TaintedValue:
    content: bytes
    taint: frozenset[str]
    content_hash: str = field(init=False)

    def __post_init__(self):
        self.content_hash = hashlib.sha256(self.content).hexdigest()


@dataclass
class DeclassificationRecord:
    content_hash: str
    authorized_by: str


class IsolationGate:
    def __init__(self, registered_tools: set[str]):
        self.registered_tools = registered_tools
        self.declassifications: dict[str, DeclassificationRecord] = {}

    def ingest(self, tool: str, content: bytes, source: str) -> TaintedValue:
        if tool not in self.registered_tools:
            # Fail closed: unregistered tool output is unknown provenance, not clean.
            return TaintedValue(content=content, taint=frozenset({f"unknown:{tool}"}))
        return TaintedValue(content=content, taint=frozenset({f"source:{source}"}))

    def transform(self, value: TaintedValue, output: bytes, tool: str) -> TaintedValue:
        # Transformation carries the full input taint set forward, plus a lineage marker.
        lineage = frozenset(value.taint) | {f"derived_via:{tool}"}
        return TaintedValue(content=output, taint=lineage)

    def declassify(self, value: TaintedValue, authorized_by: str) -> None:
        self.declassifications[value.content_hash] = DeclassificationRecord(
            content_hash=value.content_hash, authorized_by=authorized_by
        )

    def authorize_privileged_action(self, value: TaintedValue, action: str) -> None:
        if not value.taint:
            return
        record = self.declassifications.get(value.content_hash)
        if record is None:
            raise TaintProvenanceError(
                f"action {action!r} blocked: taint {sorted(value.taint)} "
                f"on content hash {value.content_hash[:12]} has no matching declassification"
            )
        # Record exists and is bound to this exact hash; proceed.
        return
