# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-whose-provenance-chain-is-intact-but-whose-write-time-context-hash-no-longer-matches-the-live-stor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-whose-provenance-chain-is-intact-but-whose-write-time-context-hash-no-longer-matches-the-live-stor.warrant.json
# Markdown SHA-256:   41d7f26071d42ebe0e3d89eb5cc44924a4ceda2f2ad97308e5aca1241654fdd3
# Code AST SHA-256:   b456082e5d778035b8c12f9671e2722fabafda110bbb6c0abfbbe5c32a2cb35c
# Verified Classes:   ProvenanceFreshnessError, Memory, Store
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceFreshnessError(RuntimeError):
    """Raised when an integrity-clean memory is stale and has no supersession path."""
    pass


@dataclass
class Memory:
    mid: str
    content: str
    scope: str
    write_epoch: int
    context_hash: str
    parent_hash: str
    signature_valid: bool
    supersedes: Optional[str] = None


@dataclass
class Store:
    scope_state: dict = field(default_factory=dict)   # scope -> bytes
    epoch: int = 0
    memories: dict = field(default_factory=dict)

    def scope_hash(self, scope: str) -> str:
        return hashlib.sha256(self.scope_state.get(scope, b"")).hexdigest()

    def supersession_path(self, mid: str) -> Optional[str]:
        seen = set()
        cur = mid
        while cur in self.memories and cur not in seen:
            seen.add(cur)
            nxt = self.memories[cur].supersedes  # edge points forward
            if nxt is None:
                return None
            if nxt in self.memories:
                return nxt
            cur = nxt
        return None


def retrieve(store: Store, mid: str) -> Memory:
    m = store.memories.get(mid)
    if m is None:
        raise ProvenanceFreshnessError(f"memory {mid} not found")
    # Integrity gate (existing behavior).
    if not m.signature_valid:
        raise ProvenanceFreshnessError(f"integrity failure: bad signature on {mid}")
    # Freshness gate.
    live = store.scope_hash(m.scope)
    if live == m.context_hash:
        return m
    # Stale but integrity-clean: require a supersession path to a fresh memory.
    succ = store.supersession_path(mid)
    if succ is None:
        raise ProvenanceFreshnessError(
            f"stale memory {mid} (scope {m.scope}) has no supersession edge; "
            f"refusing to admit on integrity alone"
        )
    return store.memories[succ]
