# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-memory-write-whose-provenance-score-is-high-but-whose-derivation-chain-crosses-a-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-memory-write-whose-provenance-score-is-high-but-whose-derivation-chain-crosses-a-compaction-boundary.warrant.json
# Markdown SHA-256:   2504e96693176aaaf646c692f26579a5920655fc16ef05d39f9447d757045e5c
# Code AST SHA-256:   466f4170902334f007d6d26c62175c8c4b44b252fa71de0e97d55d4f0692b78a
# Verified Classes:   ProvenanceChainError, MemoryRecord, ProvenanceScoringStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceChainError(RuntimeError):
    """Raised when a memory write would sever or launder its derivation chain."""
    pass


@dataclass
class MemoryRecord:
    memory_id: str
    content: str
    writer_provenance: float
    parents: list[str] = field(default_factory=list)
    # explicit per-claim provenance mapping; None means "not threaded"
    claim_provenance: Optional[dict[str, float]] = None


class ProvenanceScoringStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        self._effective: dict[str, float] = {}

    def _effective_provenance(self, memory_id: str) -> float:
        return self._effective[memory_id]

    def write(self, record: MemoryRecord) -> float:
        # First-hand observation: no parents, trust the writer.
        if not record.parents:
            effective = record.writer_provenance
            self._records[record.memory_id] = record
            self._effective[record.memory_id] = effective
            return effective

        # Derived memory. The chain must be reconstructible.
        if record.claim_provenance is None:
            # Summarizer failed to thread per-claim provenance.
            raise ProvenanceChainError(
                f"memory {record.memory_id} is derived from {record.parents} "
                f"but carries no per-claim provenance mapping; "
                f"refusing to write at writer score {record.writer_provenance:.2f}"
            )

        parent_scores = [self._effective_provenance(p) for p in record.parents]
        weakest_parent = min(parent_scores)
        effective = min(record.writer_provenance, weakest_parent)

        # Laundering guard: a derived memory may not exceed its weakest origin.
        if effective < record.writer_provenance:
            self._records[record.memory_id] = record
            self._effective[record.memory_id] = effective
            return effective

        self._records[record.memory_id] = record
        self._effective[record.memory_id] = effective
        return effective


def ingest_compaction_digest(
    store: ProvenanceScoringStore,
    digest_id: str,
    digest_text: str,
    summarizer_provenance: float,
    parent_ids: list[str],
) -> float:
    record = MemoryRecord(
        memory_id=digest_id,
        content=digest_text,
        writer_provenance=summarizer_provenance,
        parents=parent_ids,
        claim_provenance=None,  # summarizer emitted plain prose
    )
    try:
        return store.write(record)
    except ProvenanceChainError as exc:
        # Fail closed: downgrade to sentinel rather than inherit writer weight.
        raise ProvenanceChainError(
            f"compaction digest {digest_id} rejected: {exc}. "
            f"Re-emit with per-claim provenance or mark unresolved."
        ) from exc
