# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-memory-poisoning-when-write-audit-diffs-are-self-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-memory-poisoning-when-write-audit-diffs-are-self-consistent.warrant.json
# Markdown SHA-256:   937a2f8fb92392d0265fd05e2a9208c2ba0767e5d1e11e60d2982ea72a25da82
# Code AST SHA-256:   50caea24dad801e927a151808d48014030dafbf79a6606abeb599f7251705d4c
# Verified Classes:   ProvenanceClass, MemoryPoisoningError, WriteProposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceClass(Enum):
    USER_STATED = "user_stated"
    TOOL_INFERRED = "tool_inferred"
    AGENT_DERIVED = "agent_derived"


class MemoryPoisoningError(RuntimeError):
    """Raised when a write is value-consistent but provenance-unwarranted."""


@dataclass(frozen=True)
class WriteProposal:
    key: str
    old_value: str
    new_value: str
    source_event_id: str
    source_class: ProvenanceClass
    cascade_size: int


# Per-key policy: which provenance classes may mutate this key.
# Policy itself is audited; a write may not expand its own authorization set.
KEY_POLICY: dict[str, set[ProvenanceClass]] = {
    "user.timezone": {ProvenanceClass.USER_STATED},
    "user.calendar_event": {ProvenanceClass.USER_STATED, ProvenanceClass.TOOL_INFERRED},
    "cache.weather": {ProvenanceClass.TOOL_INFERRED},
}


def audit_write(proposal: WriteProposal) -> None:
    """
    Value-consistency is assumed to have passed (diff clean, invariants hold
    against the post-write snapshot). This function checks *warrant*: is the
    source class authorized to mutate this key, and is the cascade bounded?
    """
    allowed = KEY_POLICY.get(proposal.key)
    if allowed is None:
        # Unknown key: refuse until a policy is registered. Do not default-allow.
        raise MemoryPoisoningError(
            f"no provenance policy for key {proposal.key!r}; refusing write "
            f"from {proposal.source_class.value} (event {proposal.source_event_id})"
        )

    if proposal.source_class not in allowed:
        raise MemoryPoisoningError(
            f"unwarranted write to {proposal.key!r}: source class "
            f"{proposal.source_class.value} not in {sorted(c.value for c in allowed)}; "
            f"event {proposal.source_event_id} (diff was value-consistent — "
            f"this is the self-consistent poisoning case)"
        )

    # Cascade writes that rewrite dependent keys in one transaction are the
    # signature of a baseline-moving poison; force proposal/commit split.
    if proposal.cascade_size > 1:
        raise MemoryPoisoningError(
            f"cascade write of size {proposal.cascade_size} on {proposal.key!r} "
            f"requires pre-transaction diff against prior snapshot; "
            f"event {proposal.source_event_id}"
        )


def apply_write(proposal: WriteProposal, store: dict[str, str]) -> None:
    audit_write(proposal)
    store[proposal.key] = proposal.new_value
