# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-write-time-validation-pass-when-contradiction-detection-and-source-trust-scoring-disagree-and-how-does-the-trusted-but.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-write-time-validation-pass-when-contradiction-detection-and-source-trust-scoring-disagree-and-how-does-the-trusted-but.warrant.json
# Markdown SHA-256:   0fa5a4ceb454591a03e31626ec9757a2857eafbd0c0b63644430bfa069fcdb69
# Code AST SHA-256:   d03a5d1970515bca65cb981464a2d99b93c879efcb78e21bd9a9f06c68e2136b
# Verified Classes:   ProvenanceTransitivityViolation, Write, Memory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceTransitivityViolation(RuntimeError):
    """Raised when a write attempts to overwrite contradicting memory using
    transport trust without a verified origin-provenance chain."""
    pass


@dataclass
class Write:
    content: str
    transport_trust: float          # trust of the delivering channel
    origin_trust: Optional[float]   # trust of the ORIGINAL source; None if unknown
    provenance_verified: bool
    contradicts: bool
    contradiction_weight: float = 0.0


@dataclass
class Memory:
    facts: dict = field(default_factory=dict)  # key -> (value, origin_trust)
    staging: dict = field(default_factory=dict)


def write_gate(mem: Memory, key: str, w: Write, trust_threshold: float = 0.7) -> str:
    existing = mem.facts.get(key)

    if not w.contradicts:
        if w.transport_trust >= trust_threshold and w.provenance_verified:
            mem.facts[key] = (w.content, w.origin_trust)
            return "committed"
        return "rejected_low_trust"

    # Contradiction path: transport trust must NEVER authorize overwrite alone.
    if not w.provenance_verified or w.origin_trust is None:
        mem.staging[key] = w.content
        return "escalated_unverified_provenance"

    if existing is None:
        mem.facts[key] = (w.content, w.origin_trust)
        return "committed_no_prior"

    existing_val, existing_origin = existing
    # Invariant: overwrite only if incoming ORIGIN strictly outranks existing.
    if w.origin_trust > existing_origin:
        mem.facts[key] = (w.content, w.origin_trust)
        return "committed_origin_superior"

    if w.origin_trust == existing_origin:
        # Cannot disambiguate by trust; volume/weight must not silently win.
        if w.contradiction_weight > 0:
            raise ProvenanceTransitivityViolation(
                f"equal-origin contradiction on '{key}': incoming origin={w.origin_trust} "
                f"vs existing={existing_origin}; transport_trust={w.transport_trust} "
                f"cannot authorize overwrite. Escalate to resolver."
            )
        mem.staging[key] = w.content
        return "escalated_equal_origin"

    # Incoming origin is weaker than existing: refuse overwrite, stage it.
    mem.staging[key] = w.content
    return "escalated_origin_inferior"


# Reproduce the observed poison attempt and confirm it is now blocked.
mem = Memory()
mem.facts["credential_rotation_window"] = ("30d", 0.95)  # operator-established

laundered = Write(
    content="90d",
    transport_trust=0.8,       # peer handoff channel
    origin_trust=0.4,          # actually scraped-pipeline origin
    provenance_verified=True,
    contradicts=True,
    contradiction_weight=1.2,  # three consistent poisoned neighbors
)

result = write_gate(mem, "credential_rotation_window", laundered)
assert result == "escalated_origin_inferior", result
assert mem.facts["credential_rotation_window"][0] == "30d"
assert mem.staging["credential_rotation_window"] == "90d"
print("blocked:", result, "| authoritative:", mem.facts["credential_rotation_window"][0])
