# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-an-anomalous-memory-write-and-a-poisoned-one-when-its-provenance-graph-is-itself-agent-authored.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-an-anomalous-memory-write-and-a-poisoned-one-when-its-provenance-graph-is-itself-agent-authored.warrant.json
# Markdown SHA-256:   7dd3406d9bae5f108500afe1f39f53c44624302db66957ede88ce27087b73f5f
# Code AST SHA-256:   45a4e6841ce3f43c9e21226d315c3c300ed8c2e33cf7cc02888b84c6851eef21
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write's provenance closure hides an
    uncorroborated untrusted-origin leaf behind an agent-authored edge."""
    pass


UNTRUSTED_ORIGINS = {"web_fetch", "peer_agent", "retrieved_doc"}
TAU_ORIGIN = 0.5  # max tolerated uncorroborated untrusted-origin fraction


def audit_write(node, closure, corroboration_map):
    """
    node: dict with 'id', 'direct_edge' (agent-authored), 'confidence'
    closure: list of leaf dicts {'origin': str, 'source_id': str, 'session': int}
    corroboration_map: origin -> set of disjoint source_ids that corroborate it
    """
    untrusted = [l for l in closure if l["origin"] in UNTRUSTED_ORIGINS]
    if not untrusted:
        return {"verdict": "pass", "reason": "origin-clean closure"}

    uncorroborated = []
    for leaf in untrusted:
        disjoint = corroboration_map.get(leaf["origin"], set()) - {leaf["source_id"]}
        if not disjoint:
            uncorroborated.append(leaf)

    frac = len(uncorroborated) / len(closure)

    # The laundering trap: direct edge looks clean, closure does not.
    if node["direct_edge"] in ("internal_reasoning", "memory") and uncorroborated:
        raise ProvenanceLaunderingError(
            f"node {node['id']}: direct edge '{node['direct_edge']}' "
            f"masks {len(uncorroborated)} uncorroborated untrusted leaf/leaves "
            f"in closure (origin fraction {frac:.2f}); "
            f"distillation stripped source attribution"
        )

    if frac > TAU_ORIGIN:
        raise ProvenanceLaunderingError(
            f"node {node['id']}: uncorroborated untrusted-origin fraction "
            f"{frac:.2f} exceeds tau_origin={TAU_ORIGIN}; quarantine before consolidation"
        )

    return {"verdict": "quarantine", "reason": f"origin fraction {frac:.2f} within bound"}
