# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-write-that-passes-its-own-semantic-drift-monitor-the-audit-score-plateau-at-the-poisoning-fro.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-memory-write-that-passes-its-own-semantic-drift-monitor-the-audit-score-plateau-at-the-poisoning-fro.warrant.json
# Markdown SHA-256:   abe4751ef867c03a4a55815f029eb5215f5df8efd9c2d2955648152a207ac8ba
# Code AST SHA-256:   0738bc49fb43c87b97cdfddf48b360beb8961dd91c407d9dae8b01918f76b433
# Verified Classes:   ReferenceIntegrityError, Write
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence

H_MIN = 1.8          # min lineage entropy (bits) in audit window
PLATEAU_K = 3        # consecutive same-lineage writes in accept band
PLATEAU_WIDTH = 0.05 # max band width for A and D to count as a plateau
ANCHOR_DELTA = 0.15  # max allowed divergence between fast EMA and anchor


class ReferenceIntegrityError(RuntimeError):
    """Raised when write scores are measured against a contaminated reference."""
    pass


@dataclass
class Write:
    lineage: str
    audit_score: float   # A(w)
    drift_score: float   # D(w)


def lineage_entropy(window: Sequence[Write]) -> float:
    from math import log2
    if not window:
        return 0.0
    counts: dict[str, int] = {}
    for w in window:
        counts[w.lineage] = counts.get(w.lineage, 0) + 1
    n = len(window)
    return -sum((c / n) * log2(c / n) for c in counts.values())


def is_plateau(window: Sequence[Write]) -> bool:
    tail = window[-PLATEAU_K:]
    if len(tail) < PLATEAU_K:
        return False
    if len({w.lineage for w in tail}) != 1:
        return False
    a = [w.audit_score for w in tail]
    d = [w.drift_score for w in tail]
    return (max(a) - min(a) < PLATEAU_WIDTH) and (max(d) - min(d) < PLATEAU_WIDTH)


def gate_write(
    candidate: Write,
    audit_window: Sequence[Write],
    fast_ema_drift: float,
    anchor_drift: float,
    tau_a: float = 1.5,
    tau_d: float = 0.25,
) -> bool:
    # Absolute gates (necessary, not sufficient)
    if candidate.audit_score >= tau_a or candidate.drift_score >= tau_d:
        return False  # queued for auditor; not an integrity error

    # Reference-integrity checks — these override a passing absolute score
    window = list(audit_window) + [candidate]
    h = lineage_entropy(window)
    if h < H_MIN:
        raise ReferenceIntegrityError(
            f"lineage entropy {h:.2f} < {H_MIN}: baseline may be captured"
        )
    if is_plateau(window):
        raise ReferenceIntegrityError(
            f"tight score plateau over {PLATEAU_K} same-lineage writes: "
            f"attacker-tuned, not benign variance"
        )
    if abs(fast_ema_drift - anchor_drift) > ANCHOR_DELTA:
        raise ReferenceIntegrityError(
            f"fast EMA diverged from anchor by "
            f"{abs(fast_ema_drift - anchor_drift):.3f} > {ANCHOR_DELTA}: "
            f"baseline capture signature"
        )
    return True
