# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-quarantines-a-tainted-tool-output-but-the-downstream-planner-has-already-committed-the-derived-subgoal-to-working-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-quarantines-a-tainted-tool-output-but-the-downstream-planner-has-already-committed-the-derived-subgoal-to-working-memory.warrant.json
# Markdown SHA-256:   c354504a4afc1159313f308649bd16a9ec65b9d6c09244df904874a5e311d7e7
# Code AST SHA-256:   f01e44f2d8c7d654d9990de2fabb326b799fff05fbc72b3bd9b307204643a3e2
# Verified Classes:   TaintState, DerivedFromQuarantineError, MemoryItem, ProvenanceGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintState(Enum):
    CLEAN = "clean"
    TAINTED_DIRECT = "tainted:direct"      # payload itself flagged
    TAINTED_DERIVED = "tainted:derived"    # descendant of a quarantined artifact
    QUARANTINED = "quarantined"            # terminal; not a retryable error


class DerivedFromQuarantineError(RuntimeError):
    """Raised when a planner attempts to act on state whose provenance
    chain terminates at a quarantined artifact."""


@dataclass
class MemoryItem:
    key: str
    value: str
    source: str                            # e.g. "pending:tool_call_17"
    taint: TaintState = TaintState.CLEAN
    acted_upon: bool = False


@dataclass
class ProvenanceGraph:
    items: dict[str, MemoryItem] = field(default_factory=dict)
    quarantined_calls: set[str] = field(default_factory=set)

    def quarantine(self, call_id: str) -> None:
        self.quarantined_calls.add(call_id)
        # Forward walk: mark every descendant of this call as derived-tainted.
        for item in self.items.values():
            if item.source == f"pending:{call_id}":
                item.taint = TaintState.TAINTED_DERIVED

    def commit_action(self, key: str, action: str) -> None:
        item = self.items.get(key)
        if item is None:
            raise DerivedFromQuarantineError(f"unknown memory key {key!r}")
        if item.taint in (TaintState.TAINTED_DERIVED, TaintState.QUARANTINED):
            if item.acted_upon:
                # Effects already escaped the boundary: fail closed, escalate.
                raise DerivedFromQuarantineError(
                    f"action {action!r} consumes {key!r} whose provenance "
                    f"terminates at quarantined call; effects may have escaped "
                    f"the sandbox and cannot be rolled back by re-planning"
                )
            raise DerivedFromQuarantineError(
                f"action {action!r} blocked: {key!r} is {item.taint.value}; "
                f"re-derive from an untainted source before acting"
            )
        item.acted_upon = True


# --- reproduction of the observed trace -----------------------------------
g = ProvenanceGraph()
g.items["assumed_window"] = MemoryItem(
    key="assumed_window", value="45 days", source="pending:tool_call_17"
)
g.quarantine("tool_call_17")               # injection flagged at return
# planner now tries to draft the reply on the laundered assumption
g.commit_action("assumed_window", "draft_reply")
