# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-tainted-provenance-before-a-tool-output-write-is-admitted-to-durable-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-tainted-provenance-before-a-tool-output-write-is-admitted-to-durable-memory.warrant.json
# Markdown SHA-256:   75d5e224208f5d0d9425d8ed7ae37d7e4ed7c9d809f75364a3f7c4b8f46ca923
# Code AST SHA-256:   6f62e99be4c06a6f760a53448e706bacde20120c4afe5c9c04161544ee001df4
# Verified Classes:   ProvenanceLaunderingError, Envelope, MemoryWrite, ProvenanceLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

TRUSTED = "trusted"
UNTRUSTED = "untrusted"

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write declares provenance weaker than its cited inputs."""
    pass

@dataclass(frozen=True)
class Envelope:
    seg_id: str
    source: str
    trust: str
    taint: int  # bitfield; nonzero means tainted

@dataclass
class MemoryWrite:
    content: str
    cited_segments: list[str]
    declared_trust: str
    declared_taint: int

class ProvenanceLedger:
    def __init__(self) -> None:
        self._segments: dict[str, Envelope] = {}

    def register(self, env: Envelope) -> None:
        self._segments[env.seg_id] = env

    def join(self, cited: Iterable[str]) -> Envelope:
        cited = list(cited)
        if not cited:
            # No citation => cannot verify => must fail closed.
            return Envelope(seg_id="<none>", source="unknown", trust=UNTRUSTED, taint=0b11)
        taint = 0
        trust = TRUSTED
        for seg_id in cited:
            env = self._segments.get(seg_id)
            if env is None:
                # Unverifiable citation: fail closed, do not launder.
                return Envelope(seg_id=seg_id, source="unknown", trust=UNTRUSTED, taint=0b11)
            taint |= env.taint
            if env.trust == UNTRUSTED:
                trust = UNTRUSTED
        return Envelope(seg_id="<join>", source="join", trust=trust, taint=taint)

    def admit(self, write: MemoryWrite) -> Envelope:
        joined = self.join(write.cited_segments)
        # Declared provenance may not be stronger than the join.
        declared_weaker = (
            write.declared_taint < joined.taint
            or (write.declared_trust == TRUSTED and joined.trust == UNTRUSTED)
        )
        if declared_weaker:
            raise ProvenanceLaunderingError(
                f"write cites tainted/untrusted inputs {write.cited_segments} "
                f"(join taint={joined.taint:#b}, trust={joined.trust}) but declared "
                f"taint={write.declared_taint:#b}, trust={write.declared_trust}"
            )
        # Admit with the join, not the declaration.
        return joined
