# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-memory-i-wrote-during-this-task-and-memory-i-retrieved-from-a-shared-store.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-memory-i-wrote-during-this-task-and-memory-i-retrieved-from-a-shared-store.warrant.json
# Markdown SHA-256:   d2744e3046c5ec891a0731a09aab036585a3630f03dc6fa50c27af934630d362
# Code AST SHA-256:   3e1401b56936058d9676abf2adbd57daae294edd02b4ac59f34cdc1de3d15b0a
# Verified Classes:   ProvenanceLaunderingError, SourceChain, MemoryRecord, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TRUST_LEVELS = {"self": 1.0, "peer": 0.6, "untrusted_tool": 0.2, "web": 0.1}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write or transform would upgrade provenance trust."""


@dataclass
class SourceChain:
    origins: list[str]  # ordered list of origin tags, e.g. ["web", "self"]

    def min_trust(self) -> float:
        if not self.origins:
            raise ProvenanceLaunderingError(
                "empty source chain: cannot compute minimum trust; "
                "refusing to write a record with undefined provenance"
            )
        unknown = [o for o in self.origins if o not in TRUST_LEVELS]
        if unknown:
            raise ProvenanceLaunderingError(
                f"unknown provenance origin(s) {unknown!r}; "
                "refusing to guess a trust level"
            )
        return min(TRUST_LEVELS[o] for o in self.origins)


@dataclass
class MemoryRecord:
    content: str
    source_chain: SourceChain
    provenance: str = field(init=False)

    def __post_init__(self):
        # provenance is derived, never set by the caller
        self.provenance = min(
            self.source_chain.origins, key=lambda o: TRUST_LEVELS[o]
        )


class MemoryStore:
    def __init__(self):
        self._records: list[MemoryRecord] = []

    def write(self, content: str, source_chain: Optional[SourceChain]) -> MemoryRecord:
        if source_chain is None:
            raise ProvenanceLaunderingError(
                "write() called without a source_chain; "
                "a caller that cannot name its source cannot write"
            )
        # force evaluation of min_trust to validate the chain before persisting
        source_chain.min_trust()
        rec = MemoryRecord(content=content, source_chain=source_chain)
        self._records.append(rec)
        return rec

    def transform(self, records: list[MemoryRecord], new_content: str) -> MemoryRecord:
        if not records:
            raise ProvenanceLaunderingError("transform() with no input records")
        # propagate the minimum trust across ALL inputs; never set provenance
        combined = SourceChain(
            origins=[o for r in records for o in r.source_chain.origins]
        )
        return self.write(new_content, combined)

    def retrieve(self, query: str, k: int, min_trust: float = 0.5):
        # trust weighting is derived and correct only because write-path held
        scored = sorted(
            self._records,
            key=lambda r: TRUST_LEVELS[r.provenance],
            reverse=True,
        )
        return [
            r for r in scored
            if TRUST_LEVELS[r.provenance] >= min_trust
        ][:k]


def nightly_distill(store: MemoryStore, cluster: list[MemoryRecord], summary: str) -> MemoryRecord:
    """Distillation is a laundering opportunity; enforce min-trust propagation."""
    for rec in cluster:
        if rec.provenance not in TRUST_LEVELS:
            raise ProvenanceLaunderingError(
                f"cannot distill record with unknown provenance {rec.provenance!r}"
            )
    distilled = store.transform(cluster, summary)
    # sanity: distilled trust must equal minimum of inputs
    expected = min(TRUST_LEVELS[r.provenance] for r in cluster)
    if TRUST_LEVELS[distilled.provenance] > expected:
        raise ProvenanceLaunderingError(
            f"distillation upgraded trust from {expected} to "
            f"{TRUST_LEVELS[distilled.provenance]}; provenance laundering detected"
        )
    return distilled
