# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-poisoning-in-its-own-persistent-memory-store-when-the-poison-was-injected-through-legitimate-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-poisoning-in-its-own-persistent-memory-store-when-the-poison-was-injected-through-legitimate-consolidation.warrant.json
# Markdown SHA-256:   1ed3fa89176e6933e37f18a9ac94275f8f3e77cbfea5736363596d0b151d7ceb
# Code AST SHA-256:   98d3083eb364b4436c5b7bab6313186420a69337d38d0844b7fb209396e1a60a
# Verified Classes:   LineageCollapseError, Episode, SemanticFact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class LineageCollapseError(RuntimeError):
    """Raised when a semantic fact's support set is not lineage-independent."""


@dataclass
class Episode:
    episode_id: str
    predicate: str
    value: str
    lineage_token: str          # session id / cache key / doc hash, set at write time
    source: str


@dataclass
class SemanticFact:
    predicate: str
    value: str
    confidence: float
    supporting: list = field(default_factory=list)   # list[Episode]


def lineage_signature(episodes):
    return {e.lineage_token for e in episodes}


def consolidate(fact: SemanticFact, new_episodes):
    """Raise confidence only for lineage-disjoint corroboration; never for echoes."""
    for ep in new_episodes:
        if ep.predicate != fact.predicate or ep.value != fact.value:
            continue
        existing_lineages = lineage_signature(fact.supporting)
        if ep.lineage_token in existing_lineages:
            # Echo: same underlying observation re-surfaced. Zero new confidence.
            fact.supporting.append(ep)
            continue
        fact.supporting.append(ep)
        fact.confidence = min(1.0, fact.confidence + 0.15)

    # Invariant: a fact supported by only one lineage is a hypothesis, not a fact.
    if len(lineage_signature(fact.supporting)) < 2:
        fact.confidence = min(fact.confidence, 0.5)
        raise LineageCollapseError(
            f"fact {fact.predicate}={fact.value} supported by a single lineage "
            f"{lineage_signature(fact.supporting)}; demote to unverified and re-verify"
        )
    return fact
