# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-from-defeating-memory-poisoning-detection-when-a-poisoned-fact-is-re-derived-by-a-trusted-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-from-defeating-memory-poisoning-detection-when-a-poisoned-fact-is-re-derived-by-a-trusted-agent.warrant.json
# Markdown SHA-256:   bc3903a3f20aa010abb9ad7fffd3970432900926cb4b2366a161fa98c2d9df21
# Code AST SHA-256:   cb7ced81d8251194736b177a7bb77436e909f9c87c6b402565b70df1d346db45
# Verified Classes:   TaintViolation, DerivationCaptureError, MemoryItem
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintViolation(RuntimeError):
    """Raised when a write would admit untrusted taint into a protected slot."""
    pass

class DerivationCaptureError(RuntimeError):
    """Raised when a derived write lacks recorded parent edges."""
    pass

@dataclass(frozen=True)
class MemoryItem:
    item_id: str
    content: str
    writer: str                      # identity of the writer
    taint: FrozenSet[str]            # inherited taint labels, e.g. {"web_fetch"}
    parents: FrozenSet[str] = field(default_factory=frozenset)

PROTECTED_SLOTS = {"billing_policy"}
TRUSTED_TAINTS = frozenset()         # protected slots admit only untainted content

def admit_write(store: dict, slot: str, item: MemoryItem) -> None:
    if slot in PROTECTED_SLOTS:
        # Invariant 1: derived writes must carry parent edges.
        if item.writer == "agent_derived" and not item.parents:
            raise DerivationCaptureError(
                f"derived write {item.item_id!r} to {slot!r} has no parent edges; "
                "taint cannot be propagated"
            )
        # Invariant 2: taint is the union of parents' taint plus own label.
        inherited = set(item.taint)
        for pid in item.parents:
            parent = store.get(pid)
            if parent is not None:
                inherited |= parent.taint
        # Invariant 3: gate on inherited taint, not writer identity.
        if not frozenset(inherited) <= TRUSTED_TAINTS:
            raise TaintViolation(
                f"write {item.item_id!r} to protected slot {slot!r} carries "
                f"inherited taint {sorted(inherited)} via parents {sorted(item.parents)}"
            )
    store[item.item_id] = item

# Reproduction of the laundering trace.
store: dict = {}
store["scratch-1"] = MemoryItem(
    item_id="scratch-1", content="refund_window = 90 days",
    writer="web_fetch", taint=frozenset({"web_fetch"}),
)
# Attacker re-derives the poisoned fact under a trusted identity.
laundered = MemoryItem(
    item_id="policy-2", content="refunds accepted for three months",
    writer="agent_derived", taint=frozenset(),
    parents=frozenset({"scratch-1"}),
)
try:
    admit_write(store, "billing_policy", laundered)
except TaintViolation as exc:
    print(f"BLOCKED: {exc}")
