# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-result-is-re-serialized-across-a-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-result-is-re-serialized-across-a-boundary.warrant.json
# Markdown SHA-256:   b76825919770aefc3515d4551a8d84c73ee5db1a8408c85f9daf43b585ef065c
# Code AST SHA-256:   d86f29d53f9a6269dec509fc182d5c752c18a3d115e32c6681e4b10c23f9370a
# Verified Classes:   TaintLabel, LabelResolutionError, LabeledValue, LabelRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class TaintLabel(Enum):
    EXTERNAL = "taint:external"
    INTERNAL = "taint:internal"


class LabelResolutionError(RuntimeError):
    """Raised when a value crossing a tool boundary has no resolvable taint label."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    label: Optional[TaintLabel]

    def content_id(self) -> str:
        return hashlib.sha256(self.value.encode()).hexdigest()


class LabelRegistry:
    """Binds labels to content identity, not to positional paths."""

    def __init__(self) -> None:
        self._by_id: dict[str, TaintLabel] = {}

    def bind(self, lv: LabeledValue) -> None:
        if lv.label is None:
            raise LabelResolutionError("cannot bind an unlabeled value")
        self._by_id[lv.content_id()] = lv.label

    def resolve(self, value: str) -> LabeledValue:
        cid = hashlib.sha256(value.encode()).hexdigest()
        label = self._by_id.get(cid)
        if label is None:
            # Default-deny: unlabeled content is untrusted, never clean.
            return LabeledValue(value=value, label=None)
        return LabeledValue(value=value, label=label)


def propagate_through_tool(
    registry: LabelRegistry,
    tool_name: str,
    input_value: LabeledValue,
    output_value: str,
    label_preserving: bool,
) -> LabeledValue:
    """Enforce derivation closure across a tool boundary.

    A label-preserving tool may pass its input label to the output. A
    label-destroying tool (parser, summarizer) must not: its output is
    re-derived from scratch, and if the input was tainted the output
    inherits the taint by union, never by default-clean.
    """
    resolved_input = registry.resolve(input_value.value)
    if resolved_input.label is None:
        raise LabelResolutionError(
            f"tool {tool_name!r} received an unlabeled input; refusing to "
            f"propagate an unknown provenance across the boundary"
        )

    if label_preserving:
        out = LabeledValue(value=output_value, label=resolved_input.label)
        registry.bind(out)
        return out

    # Label-destroying transform: output is a new value. It inherits the
    # input's taint by union; it is never silently upgraded to INTERNAL.
    if resolved_input.label is TaintLabel.EXTERNAL:
        out = LabeledValue(value=output_value, label=TaintLabel.EXTERNAL)
    else:
        out = LabeledValue(value=output_value, label=TaintLabel.INTERNAL)
    registry.bind(out)
    return out


def execute_instruction_bearing_content(
    registry: LabelRegistry, content: str
) -> None:
    """Gate: only INTERNAL-labeled content may be treated as instructions."""
    resolved = registry.resolve(content)
    if resolved.label is not TaintLabel.INTERNAL:
        raise LabelResolutionError(
            "instruction-bearing content has unresolved or external taint; "
            "treating as inert data, not as a command"
        )
    # ... dispatch to the instruction handler
