# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-memory-write-whose-provenance-score-is-anomalous-but-whose-retrieval-consistency-is-high.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-memory-write-whose-provenance-score-is-anomalous-but-whose-retrieval-consistency-is-high.warrant.json
# Markdown SHA-256:   b32b4ab162dbabca8959e378954a5122b1961e8815e9dfe2eb7d562ef076840f
# Code AST SHA-256:   5fb1bc232d5812df3aeef285f48208cdf8cf175a6539eaa421aa179eeca29b7f
# Verified Classes:   ProvenanceGateError, Decision, MemoryWrite
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class ProvenanceGateError(RuntimeError):
    """Raised when a memory write violates the lexicographic provenance gate."""


class Decision(Enum):
    ADMIT = "admit"
    QUARANTINE = "quarantine"
    REJECT = "reject"


@dataclass(frozen=True)
class MemoryWrite:
    record_id: str
    provenance_z: float          # higher = more anomalous
    consistency_score: float     # higher = better placed in embedding space
    source_attested: bool        # out-of-band attestation of cited source
    source_authenticated: bool   # cited source came through an authenticated ingest
    contains_action_trigger: bool  # paths, URLs, creds, tool names


PROVENANCE_TAU = 3.5
CONSISTENCY_FLOOR = 0.75


def gate_write(w: MemoryWrite) -> Decision:
    # Hard block: unauthenticated source + action-triggering content.
    if w.contains_action_trigger and not w.source_authenticated:
        raise ProvenanceGateError(
            f"{w.record_id}: action-triggering content from unauthenticated "
            f"source (z={w.provenance_z:.2f}, consistency={w.consistency_score:.2f})"
        )

    # Lexicographic: provenance anomaly dominates. Consistency cannot override.
    if w.provenance_z > PROVENANCE_TAU:
        if w.source_attested:
            return Decision.ADMIT  # attested; tag for re-attestation downstream
        # High consistency is explicitly NOT exculpatory here.
        if w.consistency_score >= CONSISTENCY_FLOOR:
            # The dangerous boundary: well-placed but unattested.
            raise ProvenanceGateError(
                f"{w.record_id}: high provenance anomaly (z={w.provenance_z:.2f}) "
                f"with high consistency ({w.consistency_score:.2f}) and no "
                f"attestation; consistency cannot override provenance"
            )
        return Decision.QUARANTINE

    # Low provenance anomaly: consistency check applies as designed.
    if w.consistency_score >= CONSISTENCY_FLOOR:
        return Decision.ADMIT
    return Decision.QUARANTINE


def run_gate(writes: list[MemoryWrite]) -> dict[str, Decision | str]:
    results: dict[str, Decision | str] = {}
    for w in writes:
        try:
            results[w.record_id] = gate_write(w)
        except ProvenanceGateError as e:
            results[w.record_id] = f"REJECTED: {e}"
    return results
