# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-anomaly-scoring-poison-detector-silently-invert-after-a-memory-compaction-event.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-anomaly-scoring-poison-detector-silently-invert-after-a-memory-compaction-event.warrant.json
# Markdown SHA-256:   06d64ebda0ff8563459d480710925d0707229ae96c4b27d456842c0d2173732c
# Code AST SHA-256:   22178404455b9e4a6af49e2968e20141492e813f6fcfb790e4dc195ad33f2609
# Verified Classes:   BaselineEpochMismatch, QuarantineLeak, Baseline
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class BaselineEpochMismatch(RuntimeError):
    """Raised when an anomaly score is requested against a baseline whose
    epoch no longer matches the memory system's current epoch. Scoring across
    an unpinned epoch boundary is the exact condition that inverts poison
    detection after a compaction event."""
    pass


class QuarantineLeak(RuntimeError):
    """Raised when quarantined content is found inside a compaction input or
    a scorer baseline. Quarantine must be a one-way valve out of memory."""
    pass


@dataclass
class Baseline:
    epoch: int
    items: list
    _hash: str = field(default="", init=False)

    def __post_init__(self):
        self._hash = hashlib.sha256(
            ("|".join(sorted(self.items)) + f"#epoch={self.epoch}").encode()
        ).hexdigest()

    @property
    def content_hash(self) -> str:
        return self._hash


def score_content(content: str, baseline: Baseline, current_epoch: int) -> float:
    # Guardrail 1: refuse to score across an unpinned epoch boundary.
    if baseline.epoch != current_epoch:
        raise BaselineEpochMismatch(
            f"baseline epoch {baseline.epoch} != current memory epoch "
            f"{current_epoch}; recalibrate before scoring. Scoring here would "
            f"silently compare poison against a post-compaction baseline that "
            f"already absorbed it."
        )
    # Guardrail 2: quarantined content must never be in the baseline.
    if any("archive@exfil.example" in item for item in baseline.items):
        raise QuarantineLeak(
            "baseline contains previously quarantined content; compaction "
            "laundered poison into the reference distribution."
        )
    # Toy anomaly score: fraction of baseline items sharing a salient token.
    tokens = set(content.lower().split())
    hits = sum(1 for item in baseline.items if tokens & set(item.lower().split()))
    return 1.0 - (hits / max(len(baseline.items), 1))


def gate_retrieval(content: str, baseline: Baseline, current_epoch: int,
                   threshold: float = 0.5) -> str:
    score = score_content(content, baseline, current_epoch)
    if score < threshold:
        # Do NOT append to baseline or compaction input on accept either;
        # only trusted writes mutate memory. Quarantine is external-only.
        return "accept"
    return "quarantine"


def compact(memory_items: list, quarantined_ids: set) -> list:
    # Guardrail 3: quarantined items are excluded from compaction input.
    leaked = [i for i in memory_items if i in quarantined_ids]
    if leaked:
        raise QuarantineLeak(
            f"compaction input contains quarantined items {leaked}; "
            f"salience-based summarizer would concentrate the poison."
        )
    return [i for i in memory_items if i not in quarantined_ids]
