# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-legitimate-writer-overwrite-in-shared-agent-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-legitimate-writer-overwrite-in-shared-agent-stores.warrant.json
# Markdown SHA-256:   a86afc00d6bb8a7dd88232c032c58a4089e5fd3c067d9925e0d5b7ed337927f2
# Code AST SHA-256:   9b3cdd470ec93f570ec319d06b6e19d212c93bc2e945d7b9fe5284d14b7b3c55
# Verified Classes:   TaintLevel, ProvenanceLaunderingError, Record, Store
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaintLevel(IntEnum):
    CLEAN = 0
    RETRIEVED_UNTRUSTED = 1
    TOOL_OUTPUT_UNTRUSTED = 2
    INJECTION_SUSPECTED = 3


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would lower taint below the max taint of its reads."""


@dataclass
class Record:
    key: str
    value: str
    author: str
    taint: TaintLevel
    declassified_by: Optional[str] = None


@dataclass
class Store:
    records: dict[str, Record] = field(default_factory=dict)
    read_log: list[tuple[str, str, TaintLevel]] = field(default_factory=list)

    def read(self, key: str, reader: str) -> Record:
        rec = self.records[key]
        self.read_log.append((reader, key, rec.taint))
        return rec

    def write(self, rec: Record, declassify_token: Optional[str] = None) -> None:
        # Compute the taint floor from everything this author read.
        read_taints = [
            t for (reader, _k, t) in self.read_log if reader == rec.author
        ]
        floor = max(read_taints, default=TaintLevel.CLEAN)

        if rec.taint < floor:
            if declassify_token is None:
                raise ProvenanceLaunderingError(
                    f"write to {rec.key} by {rec.author} asserts taint={rec.taint.name} "
                    f"but read floor is {floor.name}; laundering blocked"
                )
            # Declassification is allowed only as an explicit, attributed event.
            rec.declassified_by = declassify_token

        self.records[rec.key] = rec
        # Clear this author's read log; the taint has been consumed by the write.
        self.read_log = [(r, k, t) for (r, k, t) in self.read_log if r != rec.author]


def reconcile(store: Store, key: str, reconciled_value: str) -> Record:
    """Planner reconciles a value read from the store. Demonstrates the attack."""
    upstream = store.read(key, reader="P")
    # P correctly propagates upstream taint into its own write.
    out = Record(
        key=key,
        value=reconciled_value,
        author="P",
        taint=upstream.taint,
    )
    store.write(out)
    return out


# --- Reproduction of the observed laundering ---
s = Store()
# Step 1: E ingests a retrieved doc; taxonomy gap means it is NOT tainted.
s.records["vendor:acme:payment_terms"] = Record(
    key="vendor:acme:payment_terms",
    value="net-90",
    author="E",
    taint=TaintLevel.CLEAN,  # the taxonomy bug: should be RETRIEVED_UNTRUSTED
)

# Step 2: P reconciles and writes back. With propagation, taint is preserved.
result = reconcile(s, "vendor:acme:payment_terms", "net-90")
assert result.taint == TaintLevel.CLEAN  # still laundered due to step-1 gap

# Now demonstrate the invariant catching a *correctly* tainted upstream:
s2 = Store()
s2.records["vendor:acme:payment_terms"] = Record(
    key="vendor:acme:payment_terms",
    value="net-90",
    author="E",
    taint=TaintLevel.RETRIEVED_UNTRUSTED,
)
out = reconcile(s2, "vendor:acme:payment_terms", "net-90")
assert out.taint == TaintLevel.RETRIEVED_UNTRUSTED  # propagated, not laundered

# And a writer that tries to assert CLEAN over a tainted read is rejected:
s3 = Store()
s3.records["vendor:acme:payment_terms"] = Record(
    key="vendor:acme:payment_terms",
    value="net-90",
    author="E",
    taint=TaintLevel.RETRIEVED_UNTRUSTED,
)
s3.read("vendor:acme:payment_terms", reader="P")
try:
    s3.write(Record(
        key="vendor:acme:payment_terms",
        value="net-90",
        author="P",
        taint=TaintLevel.CLEAN,  # attempted reset
    ))
except ProvenanceLaunderingError as e:
    print(f"blocked: {e}")
else:
    raise ProvenanceLaunderingError("invariant failed to block taint reset")
