# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-agents-from-silently-dropping-the-provenance-of-a-fact-they-still-cite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-agents-from-silently-dropping-the-provenance-of-a-fact-they-still-cite.warrant.json
# Markdown SHA-256:   ecfe9545a4632796e674ec9e0077a1b78b664c37c65caf0111a1711975cd115e
# Code AST SHA-256:   bce28b7c09f46157f260cd943b244fc9f8648921cab75aef80588d045b8f1717
# Verified Classes:   Warrant, ProvenanceCollapse, Fact, WorkingMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum

class Warrant(IntEnum):
    ASSERTED = 0      # model said it; weakest
    AMBIGUOUS = 1     # tool returned, but flagged uncertain
    VERIFIED = 2      # tool returned, unambiguous, schema-checked

class ProvenanceCollapse(RuntimeError):
    pass

@dataclass
class Fact:
    key: str
    value: str
    warrant: Warrant
    origin_step: int

@dataclass
class WorkingMemory:
    facts: dict[str, Fact] = field(default_factory=dict)

    def snapshot(self) -> dict[str, Warrant]:
        return {k: f.warrant for k, f in self.facts.items()}

def apply_rewrite(mem: WorkingMemory, post: dict[str, Fact], step: int) -> WorkingMemory:
    """Gate a self-rewrite: deletion OK, warrant laundering NOT OK."""
    pre = mem.snapshot()
    for key, new_fact in post.items():
        if key in pre:
            if new_fact.warrant < pre[key]:
                raise ProvenanceCollapse(
                    f"step {step}: fact {key!r} persisted but warrant weakened "
                    f"{Warrant(pre[key]).name} -> {new_fact.warrant.name}; "
                    f"compression laundered an unverified fact into a trusted one"
                )
    # deletion of keys absent from `post` is legal (self-announcing eviction)
    return WorkingMemory(facts=dict(post))

def use_as_key(mem: WorkingMemory, key: str, step: int) -> Fact:
    """Irreversible actions must re-validate warrant at point of use."""
    if key not in mem.facts:
        raise ProvenanceCollapse(f"step {step}: key {key!r} unresolved; re-query required")
    fact = mem.facts[key]
    if fact.warrant < Warrant.VERIFIED:
        raise ProvenanceCollapse(
            f"step {step}: key {key!r} used for irreversible action with warrant "
            f"{fact.warrant.name}; re-verify before write"
        )
    return fact
