# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-stale-memory-and-poisoned-memory-when-write-audit-logs-and-cross-agent-consistency-checks-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-stale-memory-and-poisoned-memory-when-write-audit-logs-and-cross-agent-consistency-checks-disagree.warrant.json
# Markdown SHA-256:   f6e2dd33327b479e5d0fa3e5ae830a1ebe5da09bfdb56abc9093152572ec951e
# Code AST SHA-256:   83da2d7e5ec55f8020c2c013214b602d33af9e7f8e72c1859906582522d3d15f
# Verified Classes:   MemoryPoisoningIndeterminate, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class MemoryPoisoningIndeterminate(RuntimeError):
    """Raised when write-audit cannot disambiguate staleness from poisoning."""
    pass


class MemoryStore:
    def __init__(self, audit, peers):
        self.audit = audit          # append-only, hash-chained, independent principal
        self.peers = peers          # list of peer memory stores

    def resolve_mismatch(self, key, local_value, local_ts):
        last = self.audit.last_entry(key)
        if last is None or not self.audit.verify_chain():
            # Cannot certify absence-of-write: fail closed, never vote.
            raise MemoryPoisoningIndeterminate(
                f"audit unverifiable for key={key!r}; refusing majority resolution"
            )

        if local_value == last.payload and local_ts <= last.ts:
            return ("stale", last.payload)          # benign; refresh from peers

        if local_value == last.payload and local_ts > last.ts:
            return ("rolled_back", last.payload)    # older-than-audit, not poisoned

        # Local value diverges from every audit entry -> poisoning.
        if local_value != last.payload and not self.audit.has_entry(key, local_value):
            return ("poisoned", last.payload)       # quarantine + rollback

        raise MemoryPoisoningIndeterminate(
            f"divergence for key={key!r} matches an audited entry; cannot classify"
        )


def apply_resolution(store, key, local_value, local_ts):
    verdict, authoritative = store.resolve_mismatch(key, local_value, local_ts)
    if verdict == "poisoned":
        store.audit.flag_principal(key, reason="unaudited_divergence")
        store.write_quarantine(key, authoritative)
    return verdict, authoritative
