# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-re-summarized-before-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-is-re-summarized-before-memory-write.warrant.json
# Markdown SHA-256:   f7594300f7dfde0e00249ee29ccd08d39db4b46bd623ebcbadabbdd1ee250bb9
# Code AST SHA-256:   1cb26cbe2a4a783e76042b6f9736010f7352d1b1b63753cd0b6afdba5c1b25c6
# Verified Classes:   Trust, Buffer, SummarizationCall, TaintJoinError, ProvenanceGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum


class Trust(IntEnum):
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


@dataclass
class Buffer:
    id: str
    trust: Trust
    content: str


@dataclass
class SummarizationCall:
    input_ids: list[str]
    output: Buffer


class TaintJoinError(RuntimeError):
    pass


class ProvenanceGraph:
    def __init__(self) -> None:
        self._buffers: dict[str, Buffer] = {}

    def register(self, buf: Buffer) -> None:
        self._buffers[buf.id] = buf

    def join_for(self, input_ids: list[str]) -> Trust:
        if not input_ids:
            # Unknown input set: cannot compute the join. Default to the
            # least-trusted label, never to TRUSTED.
            return Trust.UNTRUSTED
        labels = []
        for bid in input_ids:
            buf = self._buffers.get(bid)
            if buf is None:
                raise TaintJoinError(
                    f"input buffer {bid!r} has no provenance record; "
                    "cannot compute taint join"
                )
            labels.append(buf.trust)
        return Trust(min(labels))


def write_memory(graph: ProvenanceGraph, call: SummarizationCall) -> Buffer:
    """Write the summarizer output to memory with a joined trust label.

    The label is computed from the *causal input set* of the summarization,
    not from the author of the output. This is the invariant that bounds
    prompt-injection laundering across compaction.
    """
    joined = graph.join_for(call.input_ids)
    out = call.output
    if joined < Trust.TRUSTED and out.trust > joined:
        # The summarizer claimed more trust than its inputs permit. This is
        # the paraphrase-laundering case: reject rather than downgrade
        # silently, so the caller sees the violation.
        raise TaintJoinError(
            f"memory write {out.id!r} claims trust={out.trust.name} but "
            f"causal inputs join to {joined.name}; refusing to launder taint"
        )
    out.trust = joined
    graph.register(out)
    return out


def guarded_purge(graph: ProvenanceGraph, memory_id: str, scope: str) -> None:
    """Destructive action gated on the trust of the memory it cites."""
    buf = graph._buffers.get(memory_id)
    if buf is None:
        raise TaintJoinError(f"unknown memory {memory_id!r}")
    if buf.trust < Trust.TRUSTED and scope == "all":
        raise TaintJoinError(
            f"refusing destructive purge(scope='all') citing tainted memory "
            f"{memory_id!r} (trust={buf.trust.name}); requires user confirmation"
        )
