# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-memory-poisoning-detection-from-silently-inverting-under-embedding-space-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-memory-poisoning-detection-from-silently-inverting-under-embedding-space-drift.warrant.json
# Markdown SHA-256:   9eaad8041a17e286091fe636d4143de1eb15082fe693239393d65c5568937bca
# Code AST SHA-256:   1b123d21b6040dd21eec1ec4f9d1f0b04c24aef79805452f02bf72a4f587c1d7
# Verified Classes:   CentroidInversionError, CentroidSnapshot, AuditNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional

class CentroidInversionError(RuntimeError):
    """Raised when a write would be admitted against a reference centroid it can perturb."""
    pass

@dataclass(frozen=True)
class CentroidSnapshot:
    version: int
    vector_hash: str          # hash of the frozen reference vector(s)
    attested_only: bool       # True iff built solely from externally-validated writes

@dataclass
class AuditNode:
    content_hash: str
    embedding_hash: str
    mu_hash: str              # I2: decision context, not just decision
    anomaly_score: float
    decision: str             # "accept" | "reject" | "review"

def admit_write(
    candidate_hash: str,
    score: float,
    threshold: float,
    snapshot: CentroidSnapshot,
    folds_into_trusted: bool,
) -> AuditNode:
    # I1: a write may only be auto-admitted if the reference it was scored
    # against is attested-only AND cannot be moved by this admission.
    if score <= threshold and not snapshot.attested_only:
        raise CentroidInversionError(
            f"write {candidate_hash[:12]} scored {score:.3f} <= {threshold} "
            f"against non-attested centroid v{snapshot.version}; "
            f"admission would feed the reference it was judged by (I1 violated)"
        )
    if score <= threshold and folds_into_trusted:
        raise CentroidInversionError(
            f"write {candidate_hash[:12]} admitted and folded into trusted set "
            f"in same step; reference is not immutable under admission (I1 violated)"
        )
    # I2: every node carries the snapshot identity so the decision is replayable.
    decision = "accept" if score <= threshold else "review"
    return AuditNode(
        content_hash=candidate_hash,
        embedding_hash=hashlib.sha256(candidate_hash.encode()).hexdigest(),
        mu_hash=snapshot.vector_hash,
        anomaly_score=score,
        decision=decision,
    )

def drift_alarm(mu_trusted_hash: str, mu_observed_hash: str, delta: float) -> None:
    # Shadow-centroid guard: decisions never see mu_observed, but divergence is the signal.
    if mu_trusted_hash != mu_observed_hash and delta > 0.15:
        raise CentroidInversionError(
            f"trusted/observed centroid divergence {delta:.3f} > 0.15; "
            f"halt auto-admission and route to review"
        )
