# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-audit-trail-embedding-drift-detection-collapsing-under-legitimate-semantic-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-audit-trail-embedding-drift-detection-collapsing-under-legitimate-semantic-migration.warrant.json
# Markdown SHA-256:   3a21b5f5d6b7be862cd19dfc6c331fc0251e10e3841b4caa16dfca20c1c4f805
# Code AST SHA-256:   7b51a6869db948cd4377b9a301c6e91f5d614af695fd9cf37938c41a555c72b1
# Verified Classes:   DriftFrameError, Write
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass
from typing import Sequence


class DriftFrameError(RuntimeError):
    """Raised when a drift alarm cannot be attributed to poisoning vs. frame migration."""


@dataclass(frozen=True)
class Write:
    write_id: str
    topic: str
    embedding: Sequence[float]
    parent_context_hash: str
    timestamp: int
    corroborated: bool  # provenance-independent validation flag


def cosine_distance(a: Sequence[float], b: Sequence[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0 or nb == 0:
        raise DriftFrameError("degenerate embedding: zero-norm vector cannot be scored")
    return 1.0 - dot / (na * nb)


def reconstruct_centroid(history: Sequence[Write], topic: str, as_of: int) -> list[float]:
    """Centroid of corroborated writes for a topic as it stood at `as_of`.

    Only corroborated writes enter the reference frame; uncorroborated writes
    are excluded so that a patient adversary cannot migrate the centroid.
    """
    members = [w for w in history if w.topic == topic and w.timestamp <= as_of and w.corroborated]
    if not members:
        raise DriftFrameError(f"no corroborated reference writes for topic {topic!r} at t={as_of}")
    dim = len(members[0].embedding)
    acc = [0.0] * dim
    for w in members:
        for i, v in enumerate(w.embedding):
            acc[i] += v
    return [v / len(members) for v in acc]


def classify_alarm(
    candidate: Write,
    history: Sequence[Write],
    live_centroid: Sequence[float],
    tau: float,
) -> str:
    """Decide whether a drift alarm is poisoning or frame migration.

    Returns one of: 'frame_drift', 'latent_poisoning', 'actionable_poisoning', 'clean'.
    """
    live_dist = cosine_distance(candidate.embedding, live_centroid)
    write_time_centroid = reconstruct_centroid(history, candidate.topic, candidate.timestamp)
    historical_dist = cosine_distance(candidate.embedding, write_time_centroid)

    if historical_dist < tau and live_dist >= tau:
        return "frame_drift"
    if live_dist < tau and not candidate.corroborated:
        return "latent_poisoning"
    if historical_dist >= tau and not candidate.corroborated:
        return "actionable_poisoning"
    if historical_dist >= tau and live_dist >= tau:
        raise DriftFrameError(
            f"write {candidate.write_id!r} exceeds tau against both live and "
            f"write-time centroids ({live_dist:.3f}, {historical_dist:.3f}); "
            "reference frame is inconsistent—refuse to classify until re-anchored"
        )
    return "clean"
