# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-signed-memory-write-the-trust-laundering-boundary-in-shared-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-provenance-signed-memory-write-the-trust-laundering-boundary-in-shared-agent-memory-stores.warrant.json
# Markdown SHA-256:   29baf1bae84c6c8fb1a5e9de52e0f5436a3b3ddd2a3585dc151d92b606fa739c
# Code AST SHA-256:   9783dfe8b0971bf4ec99557e02152f95d482cd013ad6be68a036c4420477aad0
# Verified Classes:   ProvenanceLaunderingError, Trust, Envelope, Memory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write's declared chain does not cover its consumed inputs."""


@dataclass(frozen=True)
class Trust:
    level: int  # higher = more trusted; 0 is the floor


TRUST_FLOOR = Trust(0)


@dataclass(frozen=True)
class Envelope:
    origin: str
    chain: FrozenSet[str]
    taint: FrozenSet[str]
    consumed: FrozenSet[str] = field(default_factory=frozenset)
    chain_incomplete: bool = False


@dataclass(frozen=True)
class Memory:
    mem_id: str
    envelope: Envelope
    payload: str


def trust_of(instance: str) -> Trust:
    return {"scout": Trust(1), "analyst": Trust(5), "curator": Trust(9)}.get(instance, TRUST_FLOOR)


def recall_weight(mem: Memory) -> Trust:
    """Weight is the meet (minimum) over the full derivation chain, floored if incomplete."""
    if mem.envelope.chain_incomplete or not mem.envelope.chain:
        return TRUST_FLOOR
    return min((trust_of(i) for i in mem.envelope.chain), default=TRUST_FLOOR)


def validate_write(write: Memory, store: dict[str, Memory]) -> Trust:
    """Accept a write only if its chain covers every consumed input; return its recall weight."""
    env = write.envelope

    if env.consumed:
        for cid in env.consumed:
            src = store.get(cid)
            if src is None:
                raise ProvenanceLaunderingError(
                    f"write {write.mem_id} cites unknown input {cid}"
                )
            if not src.envelope.chain.issubset(env.chain):
                raise ProvenanceLaunderingError(
                    f"write {write.mem_id} chain {set(env.chain)} does not cover "
                    f"input {cid} chain {set(src.envelope.chain)}"
                )
            if not src.envelope.taint.issubset(env.taint):
                raise ProvenanceLaunderingError(
                    f"write {write.mem_id} drops taint from input {cid}: "
                    f"{set(src.envelope.taint)} not in {set(env.taint)}"
                )
    else:
        # Originating write: trust capped at the writer's own level, never promoted.
        if trust_of(env.origin).level > min((trust_of(i).level for i in env.chain), default=0):
            raise ProvenanceLaunderingError(
                f"write {write.mem_id} claims chain trust above origin {env.origin}"
            )

    return recall_weight(write)


def promote(write: Memory, store: dict[str, Memory]) -> Trust:
    """Validate and store a write; reject trust-laundered provenance."""
    weight = validate_write(write, store)
    store[write.mem_id] = write
    return weight


# --- Reproduction of the laundering failure ---
if __name__ == "__main__":
    store: dict[str, Memory] = {}

    scout_write = Memory(
        mem_id="m1",
        envelope=Envelope(origin="scout", chain=frozenset({"scout"}),
                          taint=frozenset({"external"}), consumed=frozenset()),
        payload="deployment region is eu-west-2",
    )
    promote(scout_write, store)

    # Analyst summarizes m1 but re-signs as its own origin, dropping chain and taint.
    laundered = Memory(
        mem_id="m2",
        envelope=Envelope(origin="analyst", chain=frozenset({"analyst"}),
                          taint=frozenset({"internal"}), consumed=frozenset({"m1"})),
        payload="deployment region is eu-west-2 (verified)",
    )
    try:
        promote(laundered, store)
    except ProvenanceLaunderingError as e:
        print(f"REJECTED as designed: {e}")

    # Correct derivation: chain and taint carried forward, weight = min over chain.
    honest = Memory(
        mem_id="m3",
        envelope=Envelope(origin="curator",
                          chain=frozenset({"scout", "analyst", "curator"}),
                          taint=frozenset({"external", "internal"}),
                          consumed=frozenset({"m1"})),
        payload="deployment region is eu-west-2 (verified)",
    )
    print("honest recall weight:", promote(honest, store).level)  # 1, floored by scout
