# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-memory-write-before-anomaly-scoring-converges-score-lag-poisoning-and-the-dual-write-integrity-gap-in.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-memory-write-before-anomaly-scoring-converges-score-lag-poisoning-and-the-dual-write-integrity-gap-in.warrant.json
# Markdown SHA-256:   469a9513a92c65d0d9999ea75390ce120478570ea4af755cf15def51882855dc
# Code AST SHA-256:   e6cad978c6f5027aa5dc4861f341e0f595cbec98c96b813f31bdca07fe3c7c80
# Verified Classes:   BaselineCaptureError, IntegrityViolation, MemoryWrite, ScorerState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class BaselineCaptureError(RuntimeError):
    """Raised when a memory write would be scored against—and then join—an uncalibrated baseline."""
    pass


class IntegrityViolation(RuntimeError):
    """Raised when a write fails deterministic provenance/content checks independent of any score."""
    pass


@dataclass
class MemoryWrite:
    key: str
    payload: bytes
    source_agent: str
    tool_call_id: str
    signature: bytes
    signed_payload_hash: str  # hash the signature actually covers
    warrant_valid: bool


@dataclass
class ScorerState:
    namespace: str
    window_size: int
    baseline_valid: bool
    centroid_n: int


MIN_WINDOW = 50


def integrity_check(write: MemoryWrite, payload_hash: str) -> None:
    # Deterministic, no warm-up, no statistics. Runs before any scoring.
    if write.signed_payload_hash != payload_hash:
        raise IntegrityViolation(
            f"signature covers {write.signed_payload_hash!r} but payload hashes to "
            f"{payload_hash!r} for key {write.key!r}"
        )
    if not write.warrant_valid:
        raise IntegrityViolation(f"expired/invalid warrant from {write.source_agent!r}")
    if not write.tool_call_id:
        raise IntegrityViolation("unresolvable tool_call_id; provenance broken")


def admit(write: MemoryWrite, payload_hash: str, scorer: ScorerState,
          score_fn) -> str:
    # Gate 1: deterministic integrity, independent of score.
    integrity_check(write, payload_hash)

    # Gate 2: scorer must be calibrated, and the write must be baseline-inert
    # until after scoring. If not, hold — do NOT admit on a low score.
    if not scorer.baseline_valid or scorer.centroid_n < MIN_WINDOW:
        raise BaselineCaptureError(
            f"namespace {scorer.namespace!r} baseline uncalibrated "
            f"(valid={scorer.baseline_valid}, n={scorer.centroid_n}); "
            f"write to {write.key!r} held for integrity-path adjudication"
        )

    score = score_fn(write)  # computed against converged baseline
    if score >= 0.95:
        return "quarantine_for_review"
    # Commit, and only now may the write enter the baseline window.
    return "commit"
