# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-session-memory-poisoning-when-write-time-validation-passes-but-recall-time-trust-tiers-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-session-memory-poisoning-when-write-time-validation-passes-but-recall-time-trust-tiers-disagree.warrant.json
# Markdown SHA-256:   66edae2af053c70dcbf3a650cbb22ad3bc95ee2ddb6f4d7e3e89c4668dd69a8f
# Code AST SHA-256:   a2e308967a030e1a9f6f907af2074d0c9c82c8b56ebc7948972bc2d8e6ce82c9
# Verified Classes:   TrustLaunderingError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TIER_RANK = {"UNTRUSTED": 0, "OBSERVED": 1, "TRUSTED": 2, "VERIFIED": 3}


class TrustLaunderingError(RuntimeError):
    """Raised when an internal event attempts to raise a record's trust tier."""


@dataclass
class MemoryRecord:
    claim: str
    source_tier: str
    provenance: list = field(default_factory=list)  # append-only chain
    attested_by: Optional[str] = None               # external authority id, if any


def distill(episodes: list[MemoryRecord]) -> MemoryRecord:
    """Distillation must be tier-conservative: min(), never max()/mean()."""
    if not episodes:
        raise TrustLaunderingError("cannot distill empty episode set")
    min_tier = min((e.source_tier for e in episodes), key=lambda t: TIER_RANK[t])
    # Provenance is the union of constituent chains, append-only.
    chain = [p for e in episodes for p in e.provenance]
    return MemoryRecord(
        claim=" | ".join(e.claim for e in episodes),
        source_tier=min_tier,
        provenance=chain,
        attested_by=None,  # distillation never grants attestation
    )


def promote(record: MemoryRecord, signed_source: str, verify) -> MemoryRecord:
    """The ONLY trust-increasing path. Requires out-of-band signature."""
    if not verify(signed_source):
        raise TrustLaunderingError(
            f"promotion of {record.claim!r} rejected: unsigned/forged source {signed_source!r}"
        )
    record.source_tier = "VERIFIED"
    record.attested_by = signed_source
    record.provenance.append(f"signed:{signed_source}")
    return record


def recall(candidates: list[MemoryRecord], query: str, contradicts) -> list[MemoryRecord]:
    """Contradiction detection MUST run before tier filtering."""
    relevant = [c for c in candidates if query in c.claim]
    # Step 1: detect contradictions across the FULL candidate set.
    for i, a in enumerate(relevant):
        for b in relevant[i + 1:]:
            if contradicts(a.claim, b.claim):
                # Resolve by trust, but only after both are in scope.
                loser = a if TIER_RANK[a.source_tier] < TIER_RANK[b.source_tier] else b
                if loser.source_tier == "VERIFIED" and loser.attested_by is None:
                    raise TrustLaunderingError(
                        f"VERIFIED record {loser.claim!r} has no attestation "
                        f"(laundering artifact); refusing to rank"
                    )
                relevant.remove(loser)
                break
    # Step 2: rank surviving records by tier then recency.
    return sorted(relevant, key=lambda r: TIER_RANK[r.source_tier], reverse=True)


def survival_promotion_guard(record: MemoryRecord, cycles: int) -> None:
    """Explicitly reject the 'survived N cycles' anti-pattern."""
    if cycles >= 3 and record.source_tier != "VERIFIED":
        raise TrustLaunderingError(
            f"refusing survival-based promotion of {record.claim!r} "
            f"after {cycles} cycles without external attestation"
        )
