# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-label-laundering-through-legitimate-tool-mediated-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-label-laundering-through-legitimate-tool-mediated-re-derivation.warrant.json
# Markdown SHA-256:   e4059fcecd37fb56ce8f428f56d89492aac958ca3b08ac415088128f2edba9db
# Code AST SHA-256:   67b6c8738eebd4dc25e5a7aa683ca510bb80e76f827323b95f7e773f59a7896e
# Verified Classes:   TaintLaunderingError, DeclassWitness, TaintIndex
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class TaintLaunderingError(RuntimeError):
    """Raised when a trusted tool output re-derives a tainted value without a declassification witness."""
    pass


def _norm(s: str) -> str:
    return unicodedata.normalize("NFKC", s).strip().lower()


@dataclass
class DeclassWitness:
    tool: str
    justification: str
    maps_to_irrelevant: bool  # e.g. hash, boolean, bounded enum


@dataclass
class TaintIndex:
    # normalized tainted literal -> origin step
    literals: dict[str, int] = field(default_factory=dict)

    def record(self, value: str, step: int) -> None:
        self.literals[_norm(value)] = step

    def hit(self, output: str) -> Optional[int]:
        n = _norm(output)
        for lit, step in self.literals.items():
            if lit and lit in n:
                return step
        return None


def guarded_tool_call(
    tool: str,
    args: dict,
    output: str,
    arg_labels: dict[str, str],
    taint: TaintIndex,
    step: int,
    witness: Optional[DeclassWitness] = None,
) -> str:
    """Return the effective label for a tool output, or raise on laundering."""
    origin = taint.hit(output)

    if origin is None:
        # no value-identity match: normal argument-join applies
        return "TAINTED" if any(l == "TAINTED" for l in arg_labels.values()) else "TRUSTED"

    # value-identity hit: tainted value re-derived
    if witness is None:
        raise TaintLaunderingError(
            f"tool {tool!r} at step {step} re-derived tainted value from step {origin} "
            f"with no declassification witness; args={list(args)} labels={arg_labels}"
        )
    if not witness.maps_to_irrelevant:
        raise TaintLaunderingError(
            f"witness for {tool!r} does not map tainted value to irrelevant domain"
        )
    return "DECLASSIFIED"


# --- replay check over an episode ---
def replay_episode(events, taint: TaintIndex):
    for ev in events:
        label = guarded_tool_call(
            ev.tool, ev.args, ev.output, ev.arg_labels, taint, ev.step, ev.witness
        )
        if label == "TAINTED":
            taint.record(ev.output, ev.step)
