# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-memory-poisoning-from-legitimate-state-evolution-in-a-persistent-agent-store.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-memory-poisoning-from-legitimate-state-evolution-in-a-persistent-agent-store.warrant.json
# Markdown SHA-256:   5a7aa5e7bfa0ce005c2ebf880049400f7ea37a2949dae1fa91eb4a20793f033f
# Code AST SHA-256:   213c2b02e87a61e3499d542bc75d05d8c1f2753c4bf0594459924f0e9b835aa3
# Verified Classes:   UnentailedWriteError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnentailedWriteError(RuntimeError):
    """Raised when a persistent-store write has no provenance edge to a
    prior attested version or to an external input in the epoch input log."""
    pass


AUTHORITY_KEYS = frozenset({"policy", "authz", "tool_permissions", "credentials_scope"})


def attest_epoch(store, input_log, epoch):
    """
    store: dict key -> {"value":..., "prev_hash":..., "input_hash":... or None}
    input_log: set of input hashes recorded by the *tool dispatcher* this epoch.
    Returns: ("CLEAN"|"DEGRADED"|"POISONED", details)
    """
    unentailed = []
    for key, rec in store.items():
        prev_ok = rec.get("prev_hash") is not None
        input_hash = rec.get("input_hash")
        input_ok = input_hash is not None and input_hash in input_log
        if not (prev_ok or input_ok):
            unentailed.append(key)

    if not unentailed:
        return "CLEAN", {"unentailed": []}

    authority_hits = [k for k in unentailed if k.split(":")[0] in AUTHORITY_KEYS]
    if authority_hits:
        raise UnentailedWriteError(
            f"epoch {epoch}: unentailed writes on authority keys {authority_hits}; "
            f"store must be frozen and re-attested out-of-band"
        )
    return "DEGRADED", {"unentailed": unentailed}


def apply_write(store, key, value, prev_hash, input_hash, input_log):
    """Enforce the invariant at write time, not just at attest time."""
    if prev_hash is None and (input_hash is None or input_hash not in input_log):
        raise UnentailedWriteError(
            f"write to {key!r} has neither a prior attested version nor a "
            f"dispatcher-recorded input hash; refusing to persist"
        )
    store[key] = {"value": value, "prev_hash": prev_hash, "input_hash": input_hash}
