# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-time-provenance-audits-failing-under-semantic-equivalence-laundering.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-time-provenance-audits-failing-under-semantic-equivalence-laundering.warrant.json
# Markdown SHA-256:   c92ceb28c8de410df6a51fea44f5b17904a717864b2d5a6cd23e85e0ec446940
# Code AST SHA-256:   feb628e11bdde5789a4a7f6961aea14cf838640d7146464d75fd1fc66e17459b
# Verified Classes:   ProvenanceLaunderingError, SourceTurn, MemoryRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write escalates trust beyond its claim lineage."""
    pass


@dataclass(frozen=True)
class SourceTurn:
    turn_id: str
    trust_class: int  # 0=UNTRUSTED_EXTERNAL ... 3=TRUSTED_INTERNAL
    raw_text: str


@dataclass(frozen=True)
class MemoryRecord:
    text: str
    writer_class: str          # "direct" | "consolidator" | "summarizer" | "deduplicator"
    writer_trust: int
    lineage: FrozenSet[str]    # turn_ids of ALL contributing sources
    audit_hash_covers_lineage: bool


CONSOLIDATION_WRITERS = {"consolidator", "summarizer", "deduplicator"}
TRUSTED_FLOOR = 2


def audit_write(
    record: MemoryRecord,
    sources: dict[str, SourceTurn],
    prior_trust: int | None = None,
) -> None:
    """
    Write-time provenance audit. Must be invoked by an external gate,
    NOT by the writing process itself.
    """
    # 1. Lineage must be non-empty and fully resolvable.
    if not record.lineage:
        raise ProvenanceLaunderingError(
            f"record has empty lineage but writer={record.writer_class}"
        )
    missing = record.lineage - sources.keys()
    if missing:
        raise ProvenanceLaunderingError(
            f"lineage references unknown turns: {sorted(missing)}"
        )

    # 2. Effective trust cannot exceed the minimum over lineage.
    min_lineage_trust = min(sources[t].trust_class for t in record.lineage)
    if record.writer_trust > min_lineage_trust:
        raise ProvenanceLaunderingError(
            f"trust escalation: writer_trust={record.writer_trust} "
            f"> min(lineage)={min_lineage_trust} "
            f"(writer={record.writer_class}, lineage={sorted(record.lineage)})"
        )

    # 3. Consolidation writers must preserve a multi-source lineage and
    #    hash the derivation, not just the output text.
    if record.writer_class in CONSOLIDATION_WRITERS:
        if not record.audit_hash_covers_lineage:
            raise ProvenanceLaunderingError(
                "consolidation record audit_hash does not cover lineage; "
                "hash attests to output text only — laundering possible"
            )

    # 4. Monotonicity: trust may not rise without a new trusted source turn.
    if prior_trust is not None and record.writer_trust > prior_trust:
        trusted_contributors = [
            t for t in record.lineage if sources[t].trust_class >= TRUSTED_FLOOR
        ]
        if not trusted_contributors:
            raise ProvenanceLaunderingError(
                f"trust rose {prior_trust}->{record.writer_trust} with no "
                f"trusted contributor in lineage {sorted(record.lineage)}"
            )


def read_time_token_check(record: MemoryRecord, sources: dict[str, SourceTurn]) -> None:
    """High-stakes retrieval guard: numeric tokens must trace to trusted sources."""
    import re

    trusted_text = " ".join(
        sources[t].raw_text
        for t in record.lineage
        if sources[t].trust_class >= TRUSTED_FLOOR
    )
    for token in re.findall(r"\d+(?:\.\d+)?%?", record.text):
        if token not in trusted_text:
            raise ProvenanceLaunderingError(
                f"token {token!r} in trusted record absent from all trusted "
                f"lineage contributors; possible semantic-laundering"
            )


# --- Demonstration of the observed failure ---
if __name__ == "__main__":
    untrusted_doc = SourceTurn("turn-441", 0, "The vendor SLA is 99.99% uptime.")
    trusted_fact = SourceTurn("turn-102", 3, "Vendor SLA is 99.9% uptime.")
    sources = {"turn-441": untrusted_doc, "turn-102": trusted_fact}

    # The launderd record the old pipeline produced:
    laundered = MemoryRecord(
        text="Vendor SLA is 99.99% uptime (corrected).",
        writer_class="consolidator",
        writer_trust=3,
        lineage=frozenset({"turn-102"}),   # untrusted turn-441 dropped
        audit_hash_covers_lineage=False,
    )

    try:
        audit_write(laundered, sources, prior_trust=3)
    except ProvenanceLaunderingError as e:
        print(f"BLOCKED at write: {e}")

    # Even if it had been stored, read-time check catches the token:
    try:
        read_time_token_check(laundered, sources)
    except ProvenanceLaunderingError as e:
        print(f"BLOCKED at read: {e}")
