# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-provenance-weighted-retrieval-the-trust-score-inversion-at-the-distillation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-provenance-weighted-retrieval-the-trust-score-inversion-at-the-distillation-boundary.warrant.json
# Markdown SHA-256:   674ae5bdacd16a78cc1d098469613d3884ded5eed373c86ae031a672575297f9
# Code AST SHA-256:   ed2d13634914c64db3f6dedbbac84dd4eb200bb4306653f59abfb6a6dea49956
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a distillation step would increase trust above its source."""
    pass


@dataclass
class MemoryRecord:
    claim: str
    origin_weight: float          # 0.0 .. 1.0, set by origin classifier
    origin_hashes: set[str]       # content-addressed, paraphrase-stable
    read_count: int = 0
    derivation_depth: int = 0
    storage_class: str = "episodic"  # "episodic" | "semantic"


DERIVATION_DECAY = 0.85
AMPLIFICATION_ALERT = 3.0


def trust_score(rec: MemoryRecord) -> float:
    # Corroboration from distinct origin hashes, NOT read count.
    corroboration = 1.0 + (len(rec.origin_hashes) - 1) * 0.5
    decay = DERIVATION_DECAY ** rec.derivation_depth
    return min(1.0, rec.origin_weight * corroboration * decay)


def distill(rec: MemoryRecord) -> MemoryRecord:
    """Promote episodic -> semantic while conserving (never increasing) trust."""
    before = trust_score(rec)
    distilled = MemoryRecord(
        claim=rec.claim,
        origin_weight=rec.origin_weight,       # inherited, not reset to internal
        origin_hashes=set(rec.origin_hashes),  # carried, not replaced by read events
        read_count=0,
        derivation_depth=rec.derivation_depth + 1,
        storage_class="semantic",
    )
    after = trust_score(distilled)
    if after > before + 1e-9:
        raise ProvenanceLaunderingError(
            f"distillation increased trust {before:.3f} -> {after:.3f} "
            f"for claim={rec.claim!r}; origin_hashes={rec.origin_hashes}"
        )
    return distilled


def check_amplification(rec: MemoryRecord) -> None:
    if rec.read_count / max(1, len(rec.origin_hashes)) > AMPLIFICATION_ALERT:
        raise ProvenanceLaunderingError(
            f"read-amplification loop: read_count={rec.read_count}, "
            f"distinct_origin_hashes={len(rec.origin_hashes)} for claim={rec.claim!r}"
        )
