# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-provenance-laundered-contradiction-that-survives-write-time-memory-validation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-provenance-laundered-contradiction-that-survives-write-time-memory-validation.warrant.json
# Markdown SHA-256:   23a34181341e9a8fc739333dc9e98a15c1b210b13b9b72a937bb3a932af4af7e
# Code AST SHA-256:   9bfcd74705ea45c1ccf02a7167677d67218c431f9c000ac5b988f3028d406cdb
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import hashlib


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a weak-memory cluster would be promoted to a tier that
    outranks a trusted memory without provenance-distinct corroboration."""
    pass


@dataclass
class MemoryEntry:
    claim: str
    tier: str                      # "trusted" | "pending_reconciliation" | "corroborated_external"
    confidence: float
    source_artifact: Optional[str]  # stable hash of origin doc; None == unknown
    fetch_identity: str
    session: str

    def origin_fingerprint(self) -> str:
        # Unknown origin is deliberately treated as its own distinct fingerprint
        # for promotion-blocking, but callers must NOT use it to override trust.
        artifact = self.source_artifact or f"unknown:{self.fetch_identity}:{self.session}"
        return hashlib.sha256(artifact.encode()).hexdigest()


def corroboration_is_independent(a: MemoryEntry, b: MemoryEntry) -> bool:
    if a.origin_fingerprint() == b.origin_fingerprint():
        return False
    # Unknown-origin pairs are not independent evidence for promotion.
    if a.source_artifact is None or b.source_artifact is None:
        return False
    return True


def attempt_promotion(cluster: list[MemoryEntry], trusted: MemoryEntry,
                      promotion_threshold: int = 2) -> str:
    if len(cluster) < promotion_threshold:
        return "pending_reconciliation"

    distinct = 0
    seen: set[str] = set()
    for entry in cluster:
        fp = entry.origin_fingerprint()
        if fp not in seen:
            seen.add(fp)
            distinct += 1

    # Independent-witness check: count distinct source artifacts only.
    independent = sum(
        1 for i, a in enumerate(cluster)
        for b in cluster[i + 1:]
        if corroboration_is_independent(a, b)
    )
    if distinct < promotion_threshold or independent == 0:
        # Corroboration is an echo, not independent evidence. Block promotion.
        if any(e.tier == "corroborated_external" for e in cluster):
            raise ProvenanceLaunderingError(
                f"cluster of {len(cluster)} entries shares origin fingerprint(s) "
                f"{sorted(seen)}; promotion to outrank trusted memory "
                f"'{trusted.claim}' is forbidden without provenance-distinct confirmation"
            )
        return "pending_reconciliation"

    # Even with distinct origins, never overwrite trust silently: demand re-verification.
    raise ProvenanceLaunderingError(
        f"provenance-distinct cluster contradicts trusted memory '{trusted.claim}'; "
        f"reconciliation obligation emitted, promotion blocked pending re-verification"
    )
