# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-tool-calls-without-losing-them-at-the-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-tool-calls-without-losing-them-at-the-memory-write-boundary.warrant.json
# Markdown SHA-256:   089c0aee9d4f8d31d69d810406f025ace42267662cb6ed11a16491efd7913708
# Code AST SHA-256:   614e15d74da6ff91198cc88395db6d409af5a586fbd8bfad59961686de8531cc
# Verified Classes:   TaintLaunderingError, TaintLabel, TaintLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would persist tainted content above its provenance trust."""
    pass


@dataclass
class TaintLabel:
    source: str
    trust: int  # 0 = untrusted (web/tool), 1 = trusted (operator/model-authored-clean)


@dataclass
class TaintLedger:
    # fingerprint -> label
    entries: dict[str, TaintLabel] = field(default_factory=dict)

    @staticmethod
    def fingerprint(value: str) -> str:
        normalized = " ".join(value.split()).strip().lower()
        return hashlib.sha256(normalized.encode("utf-8")).hexdigest()

    def register(self, value: str, label: TaintLabel) -> None:
        self.entries[self.fingerprint(value)] = label

    def lookup(self, value: str) -> Optional[TaintLabel]:
        return self.entries.get(self.fingerprint(value))


def write_memory(
    ledger: TaintLedger,
    key: str,
    value: str,
    context_min_trust: int,
    target: str,  # "persistent" | "scratch"
) -> TaintLabel:
    matched = ledger.lookup(value)

    if matched is not None:
        effective_trust = min(matched.trust, context_min_trust)
        source = matched.source
    else:
        # Model-authored literal with no fingerprint match: provenance unknown,
        # cap trust at the context window's minimum. Fail closed on paraphrase.
        effective_trust = min(0, context_min_trust)
        source = "model:unknown-provenance"

    label = TaintLabel(source=source, trust=effective_trust)

    if label.trust == 0 and target == "persistent":
        raise TaintLaunderingError(
            f"refusing to persist key={key!r} at trust=0 "
            f"(source={source}); would cross cold-start boundary unlabeled"
        )

    ledger.register(value, label)
    return label
