# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-episodic-store-contradiction-mining-blind-spots-under-memory-poisoning.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-episodic-store-contradiction-mining-blind-spots-under-memory-poisoning.warrant.json
# Markdown SHA-256:   dd75e0459b3eaf277e4f0148c214283815d6919ed58eb02ea95f37823cbcfa34
# Code AST SHA-256:   2c98db98c55e78704d487e29571e28ee478412180b64459801b92c9125bc4465
# Verified Classes:   UncorroboratedActionError, MemoryRecord, Cluster
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UncorroboratedActionError(RuntimeError):
    """Raised when an action would be gated by a single-witness memory cluster."""


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    proposition: str          # normalized subject-predicate-object triple
    upstream_artifact: str    # raw bytes/text of the source artifact
    source_label: str         # human-readable, NOT trusted for independence

    @property
    def lineage_hash(self) -> str:
        # Causal lineage: identical upstream content collapses to one witness,
        # regardless of how many times or via which labeled path it was written.
        return hashlib.sha256(self.upstream_artifact.encode("utf-8")).hexdigest()


@dataclass
class Cluster:
    proposition: str
    records: list[MemoryRecord] = field(default_factory=list)

    def distinct_lineages(self) -> int:
        return len({r.lineage_hash for r in self.records})

    def trust_weight(self) -> int:
        # Corroboration counts witnesses, not echoes.
        return self.distinct_lineages()


def build_clusters(records: Iterable[MemoryRecord]) -> dict[str, Cluster]:
    clusters: dict[str, Cluster] = {}
    for r in records:
        clusters.setdefault(r.proposition, Cluster(r.proposition)).records.append(r)
    return clusters


def gate_action(cluster: Cluster, action: str, irreversible: bool) -> None:
    """Permit an action gated by a memory cluster only if corroborated.

    Single-witness clusters may inform reasoning but must never gate an
    irreversible action, no matter how many records echo the proposition.
    """
    if not irreversible:
        return
    if cluster.distinct_lineages() < 2:
        raise UncorroboratedActionError(
            f"Refusing irreversible action {action!r} gated by single-witness "
            f"proposition {cluster.proposition!r}: "
            f"{len(cluster.records)} record(s), "
            f"{cluster.distinct_lineages()} distinct lineage(s). "
            f"Consistency audit cannot corroborate an echoed source."
        )


# --- Trace of the observed failure -------------------------------------------
doc = "service X endpoint = host-a.internal (migration pending)"
records = [
    MemoryRecord("m1", "service_x.host=host-a", doc, "docs-page"),
    MemoryRecord("m2", "service_x.host=host-a", doc, "tool-fetch"),   # same bytes
    MemoryRecord("m3", "service_x.host=host-a", doc, "summarizer"),   # same bytes
]
cluster = build_clusters(records)["service_x.host=host-a"]

assert cluster.trust_weight() == 1, "lineage collapse must reduce echo to one witness"

try:
    gate_action(cluster, action="deploy_to_host_a", irreversible=True)
except UncorroboratedActionError as e:
    print("BLOCKED:", e)
