# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-did-not-author-provenance-laundering-in-shared-semantic-stores-and-the-per-writer-quarantine-invarian.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-write-it-did-not-author-provenance-laundering-in-shared-semantic-stores-and-the-per-writer-quarantine-invarian.warrant.json
# Markdown SHA-256:   c781183b83b01769625284dc76e781a9dd2329a7d3af047c74f54816dba76b37
# Code AST SHA-256:   6ec1a7bd72bca259045f76edf3e5c13752459b99f6ab364c424edde4821939b9
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic write cannot be attributed to a verifiable source chain."""
    pass


TRUSTED_PEER = "trusted_peer"
RAW_TOOL = "raw_tool"
UNTRUSTED = "untrusted"
QUARANTINED = "quarantined"


def route_memory_write(write: dict, author_id: str, peer_trust: dict, quarantined_ids: set) -> str:
    """
    Decide whether a semantic memory write enters the shared index or the author's quarantine.
    Returns 'shared' or 'quarantine'. Raises ProvenanceLaunderingError on unattested writes
    that must fail closed rather than be silently admitted.
    """
    chain = write.get("source_chain")

    # Fail closed on the laundering case: no provenance means unattested, not trusted.
    if chain is None or len(chain) == 0:
        raise ProvenanceLaunderingError(
            f"write {write.get('key')!r} by {author_id!r} has empty source_chain; "
            f"unattested writes are quarantined, not admitted"
        )

    weakest = None
    for src in chain:
        if src in quarantined_ids:
            return "quarantine"                      # transitive inheritance
        cls = peer_trust.get(src, UNTRUSTED)
        if cls in (RAW_TOOL, UNTRUSTED):
            return "quarantine"
        if cls == QUARANTINED:
            return "quarantine"
        weakest = cls

    if weakest == TRUSTED_PEER:
        return "shared"
    return "quarantine"
