# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-that-passes-hash-chain-integrity-but-fails-provenance-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-memory-write-that-passes-hash-chain-integrity-but-fails-provenance-replay.warrant.json
# Markdown SHA-256:   389e3969578f24c343bdb2cff82663fa8379559bb3d798dcac3f2f537d80ce8c
# Code AST SHA-256:   d24157f0de0d7bff7529bf76809dc280f522e7c4a275d3846dbcad80ee9057a1
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

SourceClass = Literal["self_observation", "first_party_computed", "auditor_attestation",
                      "peer_claim", "relayed_untrusted"]

# Monotone trust ordering: higher index = more trustworthy.
TRUST_RANK = {"relayed_untrusted": 0, "peer_claim": 1, "auditor_attestation": 2,
              "first_party_computed": 3, "self_observation": 3}

# Trust required by a query context before an entry may gate an action.
QUERY_TRUST_REQUIREMENT = {
    "decorative_context": 0,
    "brainstorm": 1,
    "gated_action": 2,
}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a hash-valid memory entry's recorded source_class is
    stronger than its replayed weakest-link provenance permits for the query."""


@dataclass
class MemoryEntry:
    payload: str
    source_class: SourceClass
    writer_id: str
    parent_hash: str
    entry_hash: str
    # Declared output trust class of the tool/peer that produced the bytes.
    transport_trust: SourceClass


def verify_hash_chain(entries: list[MemoryEntry]) -> bool:
    # Placeholder: real impl recomputes H(parent_hash || canonical(payload) || ...).
    return all(e.entry_hash for e in entries)


def replay_weakest_link(entry: MemoryEntry, parent: MemoryEntry | None) -> SourceClass:
    """Re-derive the weakest principal in the causal chain."""
    candidates = [entry.transport_trust]
    if parent is not None:
        candidates.append(parent.source_class)
    return min(candidates, key=lambda c: TRUST_RANK[c])


def gate_read_for_action(entries: list[MemoryEntry], query_context: str) -> None:
    if not verify_hash_chain(entries):
        raise ProvenanceLaunderingError("hash chain broken; store is corrupted")

    required = QUERY_TRUST_REQUIREMENT[query_context]
    parent = None
    for entry in entries:
        replayed = replay_weakest_link(entry, parent)

        # Invariant 1: recorded class must not exceed replayed weakest link.
        if TRUST_RANK[entry.source_class] > TRUST_RANK[replayed]:
            raise ProvenanceLaunderingError(
                f"entry {entry.entry_hash[:12]}: recorded source_class="
                f"{entry.source_class!r} exceeds replayed weakest-link="
                f"{replayed!r} (entitlement laundering under valid seal)"
            )

        # Invariant 2: entry may only gate an action if its replayed class
        # meets the query's trust requirement.
        if TRUST_RANK[replayed] < required:
            raise ProvenanceLaunderingError(
                f"entry {entry.entry_hash[:12]}: replayed class {replayed!r} "
                f"below query requirement for {query_context!r} "
                f"(rank {TRUST_RANK[replayed]} < {required})"
            )
        parent = entry


# Example: the day-3 rate-limit lookup.
poisoned = MemoryEntry(
    payload="API rate limit for service X is 10 req/min",
    source_class="first_party_computed",   # mislabeled during ingestion
    writer_id="agent-R",
    parent_hash="a1b2",
    entry_hash="c3d4e5f6a7b8",
    transport_trust="relayed_untrusted",   # tool merely relayed page content
)
gate_read_for_action([poisoned], query_context="gated_action")
# -> raises ProvenanceLaunderingError: recorded first_party_computed exceeds
#    replayed relayed_untrusted. Hash chain was valid; entitlement was not.
