# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-its-own-embedding-drift-monitor-s-baseline-as-ground-truth-after-a-memory-consolidation-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-its-own-embedding-drift-monitor-s-baseline-as-ground-truth-after-a-memory-consolidation-pass.warrant.json
# Markdown SHA-256:   f06ca5c3e81d73a59ef95e6b68f697fb0fe24922ca29a462ad4fb597b9b22413
# Code AST SHA-256:   d28f8647d90438008319d2811e5c35fd7846c1db9c2da836f27f37ec7d26d20d
# Verified Classes:   BaselineCaptureError, Memory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class BaselineCaptureError(RuntimeError):
    """Raised when a store-derived drift baseline has absorbed sub-threshold poison."""


@dataclass
class Memory:
    embedding: tuple[float, float]
    warrant: float
    source: str  # "episodic" | "distilled"


def cos_dist(a: tuple[float, float], b: tuple[float, float]) -> float:
    na = math.hypot(*a)
    nb = math.hypot(*b)
    if na == 0.0 or nb == 0.0:
        return 1.0
    return 1.0 - (a[0] * b[0] + a[1] * b[1]) / (na * nb)


def centroid(store: list[Memory]) -> tuple[float, float]:
    if not store:
        return (0.0, 0.0)
    return (
        sum(m.embedding[0] for m in store) / len(store),
        sum(m.embedding[1] for m in store) / len(store),
    )


def check_drift_against_anchor(
    store: list[Memory],
    b_anchor: tuple[float, float],
    tau_cumulative: float,
) -> None:
    # The invariant: drift is measured against the FROZEN anchor, never
    # against a snapshot recomputed from the store. A snapshot baseline
    # absorbs sub-threshold poison and reports healthy forever after.
    live = centroid(store)
    drift = cos_dist(live, b_anchor)
    if drift > tau_cumulative:
        raise BaselineCaptureError(
            f"cumulative drift {drift:.4f} exceeds anchor budget "
            f"{tau_cumulative:.4f}; semantic layer must be replayed from "
            f"signed episodic log, not re-anchored to current store"
        )


def consolidate(cluster: list[Memory]) -> Memory:
    # Distilled warrant MUST inherit the minimum of its inputs. Assigning a
    # fixed high warrant launders thin poison upward through the pipeline.
    if not cluster:
        raise BaselineCaptureError("cannot consolidate empty cluster")
    inherited = min(m.warrant for m in cluster)
    return Memory(
        embedding=centroid(cluster),
        warrant=inherited,
        source="distilled",
    )
