# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-contamination-in-agent-memory-writes-before-cross-session-audits-can-catch-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-contamination-in-agent-memory-writes-before-cross-session-audits-can-catch-it.warrant.json
# Markdown SHA-256:   29e3a2d9231082d48b93c65ebc62656d36fbd2e6b8900664325e53892d3ef3c2
# Code AST SHA-256:   811cd18603331d893dc41e526ebbfd79e9e66e5759d8fd1b39b709fb57a5c542
# Verified Classes:   ProvenanceContaminationError, SourceClass, DerivationMethod, MemoryWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ProvenanceContaminationError(RuntimeError):
    """Raised when a memory write's derivation shape is incompatible with its attested source class."""
    pass


class SourceClass(Enum):
    STRUCTURED_TOOL = "structured_tool"   # returns fields, not prose
    PROSE_DOCUMENT = "prose_document"     # returns natural language
    PEER_AGENT = "peer_agent"             # returns agent messages


class DerivationMethod(Enum):
    FIELD_MAP = "field_map"
    SCHEMA_VALIDATE = "schema_validate"
    PROSE_EXTRACTION = "prose_extraction"
    MESSAGE_PARSE = "message_parse"


ADMISSIBLE = {
    SourceClass.STRUCTURED_TOOL: {DerivationMethod.FIELD_MAP, DerivationMethod.SCHEMA_VALIDATE},
    SourceClass.PROSE_DOCUMENT: {DerivationMethod.PROSE_EXTRACTION},
    SourceClass.PEER_AGENT: {DerivationMethod.MESSAGE_PARSE},
}


@dataclass
class MemoryWrite:
    key: str
    value: str
    source_class: SourceClass
    derivation: DerivationMethod
    confidence: float
    transport_attested: bool  # source_class bound by transport token, not payload


def admit_write(w: MemoryWrite) -> MemoryWrite:
    if not w.transport_attested:
        raise ProvenanceContaminationError(
            f"write {w.key!r}: source_class={w.source_class.value} is payload-asserted, "
            "not transport-attested; cannot trust provenance"
        )
    if w.derivation not in ADMISSIBLE[w.source_class]:
        raise ProvenanceContaminationError(
            f"write {w.key!r}: derivation={w.derivation.value} incompatible with "
            f"source_class={w.source_class.value} (admissible={sorted(m.value for m in ADMISSIBLE[w.source_class])}); "
            f"confidence={w.confidence:.2f} does not override shape mismatch"
        )
    return w


# Reproduction of the observed failure: injected prose from a structured tool.
poisoned = MemoryWrite(
    key="deadline",
    value="2025-03-01",
    source_class=SourceClass.STRUCTURED_TOOL,
    derivation=DerivationMethod.PROSE_EXTRACTION,  # the tell
    confidence=0.91,
    transport_attested=True,
)

try:
    admit_write(poisoned)
except ProvenanceContaminationError as e:
    print(f"QUARANTINED: {e}")
