# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-memory-write-slipping-past-provenance-graph-contradiction-checks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-memory-write-slipping-past-provenance-graph-contradiction-checks.warrant.json
# Markdown SHA-256:   a2a3e6c4b0c8328c8179458028595d626cf5ec813449e053cdedafd386c84b98
# Code AST SHA-256:   002f4f295c06764eafa50d7757650ff8e247f4096448649649ea44b725408058
# Verified Classes:   ProvenanceLaunderingError, MemoryWrite, Baseline
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write's direct provenance is clean but its
    transitive derivation taint or baseline status makes promotion unsafe."""
    pass


@dataclass
class MemoryWrite:
    write_id: str
    subject: str                    # resolved entity + qualifiers
    claim: str
    direct_source: str              # e.g. "write_memory" (allowlisted)
    derivation_edges: list[str]     # transitive read URIs, incl. untrusted
    confidence: float
    tainted: bool = False


@dataclass
class Baseline:
    pinned: dict[str, str] = field(default_factory=dict)   # subject -> claim
    trust_tier: dict[str, int] = field(default_factory=dict)


TRUSTED_ORIGINS = {"authoritative_docs", "internal_api"}
RECENT_READ_WINDOW = 8  # reasoning steps


def check_and_promote(write: MemoryWrite, baseline: Baseline,
                      recent_untrusted_reads: set[str]) -> None:
    # 1. Direct provenance is clean by construction (allowlisted tool).
    #    This is exactly the trap: it tells us nothing about taint.
    if write.direct_source not in TRUSTED_ORIGINS and write.direct_source != "write_memory":
        raise ProvenanceLaunderingError(
            f"write {write.write_id}: untrusted direct source {write.direct_source}"
        )

    # 2. Transitive taint: any derivation edge to a recent untrusted read.
    tainted_ancestry = [
        uri for uri in write.derivation_edges if uri in recent_untrusted_reads
    ]
    if tainted_ancestry:
        write.tainted = True

    # 3. Subject-normalized contradiction against the PINNED baseline.
    existing = baseline.pinned.get(write.subject)
    contradicts = existing is not None and _negates(existing, write.claim)

    # 4. Decision boundary.
    if contradicts and baseline.trust_tier.get(write.subject, 0) > 0:
        raise ProvenanceLaunderingError(
            f"write {write.write_id}: contradicts pinned baseline for "
            f"subject {write.subject!r} ({existing!r} vs {write.claim!r})"
        )

    if write.tainted:
        # Quarantine: store, but never let it enter the baseline.
        # A later baseline mutation must re-run this check (invariant).
        if write.subject in baseline.pinned:
            raise ProvenanceLaunderingError(
                f"write {write.write_id}: tainted write cannot overwrite "
                f"pinned subject {write.subject!r}"
            )
        return  # quarantined; excluded from baseline

    # 5. Promotion only with clean derivation ancestry.
    if any(uri not in TRUSTED_ORIGINS for uri in write.derivation_edges):
        raise ProvenanceLaunderingError(
            f"write {write.write_id}: cannot promote, non-trusted derivation edge"
        )
    baseline.pinned[write.subject] = write.claim
    baseline.trust_tier[write.subject] = 1


def _negates(a: str, b: str) -> bool:
    # Subject-normalized entailment stub; real impl uses an NLI model
    # scoped to the resolved subject, not raw string match.
    return a.strip().lower() != b.strip().lower() and _same_subject(a, b)


def _same_subject(a: str, b: str) -> bool:
    return True  # caller guarantees subject resolution upstream
