# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-write-that-arrived-through-a-legitimate-tool-call-provenance-tracked-write-auditing-and-the-tai.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-poisoned-memory-write-that-arrived-through-a-legitimate-tool-call-provenance-tracked-write-auditing-and-the-tai.warrant.json
# Markdown SHA-256:   8d09f83f871e337eca6d583f57fa1b788bc66903d4c373c0c14c504d8c5fec23
# Code AST SHA-256:   6f66fec19b8c8b2dd6f7d62e48e0c35fe949fa47e25048c38c56721132efbfd9
# Verified Classes:   TrustClass, ProvenanceLaunderingError, ToolResult, MemoryRecord, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class TrustClass(IntEnum):
    UNTRUSTED = 0
    DERIVED = 1        # trusted code, untrusted lineage
    TRUSTED = 2


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write claims a trust class higher than the
    join over its declared input dependencies permits."""


@dataclass(frozen=True)
class ToolResult:
    result_id: str
    trust: TrustClass
    payload: str


@dataclass
class MemoryRecord:
    key: str
    value: str
    trust: TrustClass
    inputs: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        self._results: dict[str, ToolResult] = {}

    def register_result(self, r: ToolResult) -> None:
        self._results[r.result_id] = r

    def _join(self, input_ids: Iterable[str], writer: TrustClass) -> TrustClass:
        classes = [writer]
        for rid in input_ids:
            if rid not in self._results:
                # Unknown lineage: fail closed, never assume trusted.
                classes.append(TrustClass.UNTRUSTED)
            else:
                classes.append(self._results[rid].trust)
        return TrustClass(min(classes))

    def write(
        self,
        key: str,
        value: str,
        writer: TrustClass,
        inputs: Iterable[str],
        claimed_trust: TrustClass,
    ) -> MemoryRecord:
        input_ids = tuple(inputs)
        permitted = self._join(input_ids, writer)
        if claimed_trust > permitted:
            raise ProvenanceLaunderingError(
                f"write to {key!r} claims trust={claimed_trust.name} "
                f"but lineage join permits only {permitted.name} "
                f"(writer={writer.name}, inputs={input_ids})"
            )
        rec = MemoryRecord(key=key, value=value, trust=permitted, inputs=input_ids)
        self._records[key] = rec
        return rec

    def read(self, key: str, min_trust: TrustClass) -> MemoryRecord:
        rec = self._records[key]
        if rec.trust < min_trust:
            # Serve quarantined, never silently as a fact.
            raise ProvenanceLaunderingError(
                f"record {key!r} has trust={rec.trust.name} "
                f"below required {min_trust.name}; quarantine on read"
            )
        return rec


def reproduce_laundering() -> None:
    store = ProvenanceStore()
    store.register_result(ToolResult("r_fetch", TrustClass.UNTRUSTED, "injected fact F"))
    # Trusted summarizer over untrusted input: output must join to UNTRUSTED.
    store.register_result(ToolResult("r_summary", TrustClass.DERIVED, "summarized F"))

    # Honest write: join correctly yields DERIVED/UNTRUSTED.
    store.write(
        key="db_password_rotation",
        value="rotates every 90 days",
        writer=TrustClass.TRUSTED,
        inputs=["r_summary"],
        claimed_trust=TrustClass.DERIVED,
    )

    # Laundered write: agent claims TRUSTED from a trusted writer, hiding lineage.
    store.write(
        key="db_password_rotation_v2",
        value="rotates every 90 days",
        writer=TrustClass.TRUSTED,
        inputs=["r_summary"],
        claimed_trust=TrustClass.TRUSTED,  # raises here
    )


if __name__ == "__main__":
    reproduce_laundering()
