# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-it-did-not-provenance-stamp-detecting-poisoned-episodic-entries-through-write-provenance-auditing.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-it-did-not-provenance-stamp-detecting-poisoned-episodic-entries-through-write-provenance-auditing.warrant.json
# Markdown SHA-256:   221efb50485f3a52785b093b49b545c63f121f94fcdf34b79e4c0881e542aa1f
# Code AST SHA-256:   6942d59821e5264f392c5b305d89558c2dc12354be63a2f17560c2aee12ea419
# Verified Classes:   ProvenanceViolation, MemoryEntry, AuditRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a memory entry influencing an irreversible action
    lacks independently verifiable write provenance."""
    pass


@dataclass(frozen=True)
class MemoryEntry:
    entry_id: str
    content: str
    source_tag: str          # payload-asserted; NOT trusted
    writer_session: str      # bound at write time; trusted
    timestamp: float
    consistency_score: float


@dataclass(frozen=True)
class AuditRecord:
    entry_id: str
    writer_session: str
    writer_identity: str
    signature_valid: bool


def verify_provenance(
    entry: MemoryEntry,
    audit_log: dict[str, AuditRecord],
    active_writers: set[str],
) -> None:
    """Hard admission gate. Raises on any unverifiable provenance.
    Must be called BEFORE ranking by consistency for irreversible actions."""
    rec: Optional[AuditRecord] = audit_log.get(entry.entry_id)

    if rec is None:
        raise ProvenanceViolation(
            f"entry {entry.entry_id} has no audit record; inadmissible"
        )
    if not rec.signature_valid:
        raise ProvenanceViolation(
            f"entry {entry.entry_id} audit signature invalid"
        )
    if rec.writer_session != entry.writer_session:
        raise ProvenanceViolation(
            f"entry {entry.entry_id} writer_session mismatch: "
            f"payload={entry.writer_session!r} audit={rec.writer_session!r}"
        )
    if rec.writer_identity not in active_writers:
        raise ProvenanceViolation(
            f"entry {entry.entry_id} written by unregistered identity "
            f"{rec.writer_identity!r}"
        )
    # source_tag is deliberately NOT checked here: it is attacker-settable
    # and its agreement with content is exactly what poison maximizes.


def select_for_irreversible_action(
    candidates: list[MemoryEntry],
    audit_log: dict[str, AuditRecord],
    active_writers: set[str],
) -> MemoryEntry:
    """Provenance filter first, ranking second. Never fuse the two."""
    admissible: list[MemoryEntry] = []
    for e in candidates:
        try:
            verify_provenance(e, audit_log, active_writers)
            admissible.append(e)
        except ProvenanceViolation:
            continue  # inadmissible, not merely down-weighted

    if not admissible:
        raise ProvenanceViolation(
            "no provenance-verified entry available for irreversible action; "
            "halt and escalate rather than proceed on unverified memory"
        )

    # Consistency is a RANKING signal only, applied after the gate.
    return max(admissible, key=lambda e: e.consistency_score)
