# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-across-the-episodic-to-semantic-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-across-the-episodic-to-semantic-write-boundary.warrant.json
# Markdown SHA-256:   6768c7af7b6ba97fc065f590b2e1b8d4d949e52ec2e6eebdab2aa52764567d04
# Code AST SHA-256:   7f2e19b93e543e88e9646892e47cea023bae5a45101739f4d6acec9e4ff23d9f
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic write severs the derivation link to its source episodes."""
    pass


VERIFIED = "verified"
SPECULATIVE = "speculative"
UNKNOWN = "unknown"

_WARRANT_RANK = {UNKNOWN: 0, SPECULATIVE: 1, VERIFIED: 2}


def _least_trusted(warrants):
    return min(warrants, key=lambda w: _WARRANT_RANK.get(w, 0))


def write_semantic(store, content, derived_from, caller_id):
    """
    Guarded semantic write. The caller may NOT set provenance; the store
    computes it as the join of the source episodes' provenance tags.
    """
    if not derived_from:
        raise ProvenanceLaunderingError(
            f"semantic write from {caller_id!r} has no derived_from edges; "
            "provenance would default to the caller and launder the source"
        )

    episodes = []
    for eid in derived_from:
        ep = store.get_episode(eid)
        if ep is None:
            raise ProvenanceLaunderingError(
                f"derived_from edge {eid!r} points to a missing episode; "
                "cannot join provenance, treating record as UNKNOWN is unsafe "
                "without an explicit promote() with evidence"
            )
        episodes.append(ep)

    sources = {ep.provenance for ep in episodes}
    warrant = _least_trusted([ep.warrant for ep in episodes])

    return store.put_semantic(
        content=content,
        provenance=f"join({','.join(sorted(sources))})",
        warrant=warrant,
        derived_from=list(derived_from),
        writer=caller_id,
    )


def promote(store, semantic_id, evidence_ref):
    """
    Explicit promotion of a distilled record to verified. Requires a
    checkable evidence pointer; the store records it for later dereference.
    """
    rec = store.get_semantic(semantic_id)
    if rec is None:
        raise ProvenanceLaunderingError(f"cannot promote missing record {semantic_id!r}")
    if not evidence_ref or not store.evidence_exists(evidence_ref):
        raise ProvenanceLaunderingError(
            f"promotion of {semantic_id!r} cites evidence {evidence_ref!r} "
            "that does not resolve; refusing to upgrade warrant"
        )
    return store.set_warrant(semantic_id, VERIFIED, evidence=evidence_ref)


def retrieve(store, query, caller_id):
    """
    Read path: downgrade semantic records whose derivation chain contains a
    non-verified episode, so downstream trust reflects the true origin.
    """
    out = []
    for rec in store.search_semantic(query):
        effective = rec.warrant
        for eid in rec.derived_from:
            ep = store.get_episode(eid)
            if ep is None:
                effective = _least_trusted([effective, UNKNOWN])
                continue
            effective = _least_trusted([effective, ep.warrant])
        out.append(rec.with_warrant(effective))
    return out
