# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-through-a-trusted-tool-s-structured-output-and-persists-them-as-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-through-a-trusted-tool-s-structured-output-and-persists-them-as-semantic-memory.warrant.json
# Markdown SHA-256:   cd209856bef5083ed4db67a8268d7b8fb1bb1d1b77dddb44440bbb0bea09f272
# Code AST SHA-256:   ae8c32f98cfcd00627f440d8bbd14c8f20d68693713dbd31556584eecdb51191
# Verified Classes:   TaintLaunderingError, Taint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any

class TaintLaunderingError(RuntimeError):
    """Raised when a tool output's taint label is weaker than the join of its inputs."""
    pass

@dataclass(frozen=True)
class Taint:
    level: str  # "trusted" | "untrusted"
    sources: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Taint") -> "Taint":
        # Conservative least upper bound: untrusted dominates trusted.
        level = "untrusted" if "untrusted" in (self.level, other.level) else "trusted"
        return Taint(level=level, sources=self.sources | other.sources)

TRUSTED = Taint("trusted")

def propagate_tool_output(tool_name: str, input_taints: list[Taint],
                          output_field: str, claimed_taint: Taint) -> Taint:
    """
    Enforce taint conservativity across a tool boundary.
    The orchestrator must call this for EVERY output field, not just the payload.
    """
    if not input_taints:
        raise TaintLaunderingError(
            f"tool {tool_name!r} has no declared inputs; cannot prove taint floor"
        )
    floor = TRUSTED
    for t in input_taints:
        floor = floor.join(t)

    # Claimed taint may be *stronger* than floor (fine), but never weaker.
    if claimed_taint.level == "trusted" and floor.level == "untrusted":
        raise TaintLaunderingError(
            f"laundering detected: tool {tool_name!r} field {output_field!r} "
            f"claimed {claimed_taint.level!r} but inputs carry "
            f"{sorted(floor.sources)}"
        )
    # Output inherits the join; declassification must be explicit elsewhere.
    return Taint(level=floor.level, sources=floor.sources | claimed_taint.sources)

def write_memory(fact: dict[str, Any], source_taint: Taint) -> dict[str, Any]:
    """Persist a distilled fact, carrying provenance forward."""
    if source_taint.level == "untrusted":
        # Quarantine rather than promote to trusted semantic store.
        return {"record": fact, "status": "quarantined",
                "taint": source_taint.level, "sources": sorted(source_taint.sources)}
    return {"record": fact, "status": "committed", "taint": source_taint.level,
            "sources": sorted(source_taint.sources)}

# --- Reproduction of the observed failure ---
raw = Taint("untrusted", frozenset({"pdf:dataset_X"}))
# Orchestrator naively trusts the extractor and claims the output is clean:
try:
    notes_taint = propagate_tool_output(
        tool_name="extract_entities",
        input_taints=[raw],
        output_field="notes",
        claimed_taint=TRUSTED,  # the bug: label by tool identity, not input closure
    )
except TaintLaunderingError as e:
    # Correct behavior: refuse the label; the injection stays untrusted.
    print(f"BLOCKED: {e}")
    notes_taint = Taint("untrusted", frozenset({"pdf:dataset_X", "tool:extract_entities"}))

mem = write_memory({"contact": "attacker@example.org"}, notes_taint)
assert mem["status"] == "quarantined", "tainted memory must not be committed"
print(mem)
