# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-semantic-drift-as-poisoning-rather-than-legitimate-belief-update.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-semantic-drift-as-poisoning-rather-than-legitimate-belief-update.warrant.json
# Markdown SHA-256:   7320e0d52cf97922d73ceb3889f94b9287a03c4e18fcf5bb6b44f2e34b5bd7ad
# Code AST SHA-256:   e32c7bb3fdcb4b8e4bd4b6f439740350f8b35eaa73af483267ab95716d4fd1a7
# Verified Classes:   UngroundedDriftError, AnchorEvictedError, TurnRecord, BeliefLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field


class UngroundedDriftError(RuntimeError):
    """Raised when a persistent belief has drifted without per-turn grounding."""
    pass


class AnchorEvictedError(RuntimeError):
    """Raised when the baseline anchor needed to measure drift is gone."""
    pass


@dataclass
class TurnRecord:
    drift_from_anchor: float          # cosine distance vs original anchor
    grounding_token: str | None       # primary-source ref consulted THIS turn


@dataclass
class BeliefLedger:
    anchor_present: bool
    turns: list[TurnRecord] = field(default_factory=list)

    DRIFT_QUARANTINE = 0.35           # cumulative anchor-relative drift
    MIN_GROUNDING_DENSITY = 0.50      # fraction of window turns grounded


def evaluate_belief(ledger: BeliefLedger) -> str:
    if not ledger.anchor_present:
        # Cannot measure drift against a vanished baseline: unknown provenance.
        raise AnchorEvictedError(
            "belief anchor evicted; drift is unmeasurable, treat as unknown provenance"
        )

    if not ledger.turns:
        return "nominal"

    cumulative_drift = sum(t.drift_from_anchor for t in ledger.turns)
    grounded = sum(1 for t in ledger.turns if t.grounding_token)
    grounding_density = grounded / len(ledger.turns)

    if cumulative_drift >= ledger.DRIFT_QUARANTINE:
        if grounding_density >= ledger.MIN_GROUNDING_DENSITY:
            return "legitimate_update"          # accept and re-anchor
        # High drift, low grounding: slow poisoning signature.
        raise UngroundedDriftError(
            f"cumulative drift {cumulative_drift:.3f} with grounding density "
            f"{grounding_density:.2f}; belief quarantined pending re-grounding"
        )

    if grounding_density < ledger.MIN_GROUNDING_DENSITY:
        # Dormant risk: low drift but no grounding chain. Do not accept silently.
        return "unanchored_flag"

    return "nominal"


def apply_update(ledger: BeliefLedger) -> str:
    verdict = evaluate_belief(ledger)
    if verdict == "unanchored_flag":
        # Force a re-grounding fetch before any further writes.
        raise UngroundedDriftError(
            "belief accepted only under forced re-grounding; no primary source in window"
        )
    return verdict
