# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-write-time-anomaly-scores-from-poisoning-the-semantic-store-when-a-session-s-own-baseline-is-contaminated.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-write-time-anomaly-scores-from-poisoning-the-semantic-store-when-a-session-s-own-baseline-is-contaminated.warrant.json
# Markdown SHA-256:   fe211c8a36cb113b63952326dd1915575b83af5697c22105a52f5c4a08ce55aa
# Code AST SHA-256:   989da6061d45ca94af391accc54ac613d4bb758698f6189065b60abe3241699e
# Verified Classes:   BaselineContaminationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class BaselineContaminationError(RuntimeError):
    """Raised when a write is scored against a baseline it could have influenced."""
    pass


MIN_INDEPENDENT_SAMPLES = 8
ANOMALY_THRESHOLD = 2.5


def admit_write(candidate, session, store) -> str:
    baseline = store.frozen_baseline()  # pre-session snapshot, never session-derived

    if baseline.sample_count < MIN_INDEPENDENT_SAMPLES:
        # Cannot score soundly; hold rather than admit on a thin baseline.
        return "hold:insufficient_baseline"

    if candidate.shares_ancestor_with(baseline.provenance):
        raise BaselineContaminationError(
            f"write {candidate.id} shares retrieval ancestry with scoring baseline; "
            f"score is not independent evidence"
        )

    z = baseline.zscore(candidate.embedding)
    if z >= ANOMALY_THRESHOLD:
        # High score against a CLEAN baseline: genuine anomaly, quarantine.
        store.quarantine(candidate, reason=f"z={z:.2f}")
        return "quarantine"

    corroboration = store.independent_corroboration(
        candidate, exclude_ancestors=baseline.provenance
    )
    if corroboration < 1:
        # Low score but no independent support: do not admit on score alone.
        return "hold:needs_independent_corroboration"

    store.commit(candidate)
    return "admit"
