# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-at-the-tool-result-re-entry-boundary-during-skill-injection-containment.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-at-the-tool-result-re-entry-boundary-during-skill-injection-containment.warrant.json
# Markdown SHA-256:   e8870e11dda866fbfb4858a117900b4665a4b566dc100fae02c3bc400a25ecdc
# Code AST SHA-256:   171780524cd3d7057612f970abf5e856e03963d7ca006782486806fc367155c9
# Verified Classes:   TaintLaunderingError, TaintedValue, TaintStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

# Taint lattice: 0 = clean, 1 = USER_NOTES, 2 = SUMMARY, 3 = EXTERNAL, 4 = TOP
TAINT_ORDER = {"CLEAN": 0, "USER_NOTES": 1, "SUMMARY": 2, "EXTERNAL": 3, "TOP": 4}


class TaintLaunderingError(RuntimeError):
    """Raised when a tool result's label is lower than the join of its actual inputs."""


@dataclass
class TaintedValue:
    payload: str
    label: str  # one of TAINT_ORDER keys


def join(labels: Iterable[str]) -> str:
    worst = "CLEAN"
    for lab in labels:
        if TAINT_ORDER[lab] > TAINT_ORDER[worst]:
            worst = lab
    return worst


@dataclass
class TaintStore:
    # cell name -> accumulated taint label (join-into, never overwrite)
    cells: dict = field(default_factory=dict)

    def write(self, cell: str, value: TaintedValue) -> None:
        prev = self.cells.get(cell, "CLEAN")
        self.cells[cell] = join([prev, value.label])

    def read(self, cell: str) -> str:
        return self.cells.get(cell, "CLEAN")


def enforce_reentry(
    tool_name: str,
    declared_class: str,
    actual_arg_labels: Iterable[str],
    actual_store_reads: Iterable[str],
    result: TaintedValue,
) -> TaintedValue:
    """Re-entry guard: result label must dominate the join of everything the tool
    actually consumed (args AND stores), joined with its declared class."""
    consumed = list(actual_arg_labels) + list(actual_store_reads) + [declared_class]
    required = join(consumed)
    if TAINT_ORDER[result.label] < TAINT_ORDER[required]:
        raise TaintLaunderingError(
            f"tool {tool_name!r} returned label {result.label!r} but consumed "
            f"values joining to {required!r}; declared class {declared_class!r} "
            f"cannot lower taint. Refusing to relabel."
        )
    # Raise, never lower: result carries at least the required join.
    return TaintedValue(payload=result.payload, label=required)


def run_chain() -> None:
    store = TaintStore()
    # Hop 1: external doc summarized; declared class SUMMARY but actual input EXTERNAL.
    summary = enforce_reentry(
        "fetch_and_summarize",
        declared_class="SUMMARY",
        actual_arg_labels=["EXTERNAL"],
        actual_store_reads=[],
        result=TaintedValue("...", "SUMMARY"),
    )
    # Hop 2: write to notes store; the store cell must accumulate EXTERNAL.
    store.write("notes:42", summary)
    # Hop 3: read_note must join the cell's taint out, not the declared USER_NOTES.
    read_label = store.read("notes:42")
    try:
        enforce_reentry(
            "read_note",
            declared_class="USER_NOTES",
            actual_arg_labels=[],
            actual_store_reads=[read_label],
            result=TaintedValue("...", "USER_NOTES"),
        )
    except TaintLaunderingError:
        # Correct outcome: the laundered USER_NOTES label is rejected because the
        # store cell accumulated EXTERNAL. send_email is never reached.
        print("contained: lateral movement to send_email blocked")
        return
    raise TaintLaunderingError("taint decayed across notes store; containment failed")


if __name__ == "__main__":
    run_chain()
