# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-unauthorized-memory-mutation-when-the-audit-trail-is-reconstructed-from-the-same-context-it-is-auditing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-unauthorized-memory-mutation-when-the-audit-trail-is-reconstructed-from-the-same-context-it-is-auditing.warrant.json
# Markdown SHA-256:   e775e4ccbf675da021894487f87d8a8ff385f312c668615353b966951dfe8aff
# Code AST SHA-256:   43461e5b57319b557fc4aad6fe00da02244c31032546d1d32873f88243996240
# Verified Classes:   ProvenanceConservationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceConservationError(RuntimeError):
    """Raised when a memory mutation drops or fabricates source coverage."""
    pass


def audit_mutation_coverage(episodes, facts, changelog_status):
    """
    episodes: dict[id -> {"status": "raw"|"consolidated"}], immutable source log.
    facts: list of {"id": str, "source_ids": set[str]} currently in semantic store.
    changelog_status: the in-context narrative verdict, e.g. "LINEAGE_CONSISTENT".

    Returns a verdict dict. Raises ProvenanceConservationError on violation.
    """
    marked_consumed = {eid for eid, e in episodes.items()
                       if e["status"] == "consolidated"}
    cited = set()
    for f in facts:
        cited |= set(f["source_ids"])

    unaccounted = marked_consumed - cited          # consumed but no descendant: lossy merge
    phantom = cited - set(episodes.keys())        # cites a source that never existed: fabrication

    if unaccounted or phantom:
        raise ProvenanceConservationError(
            f"Provenance conservation violated. "
            f"unaccounted_sources={sorted(unaccounted)} "
            f"phantom_sources={sorted(phantom)} "
            f"in_context_verdict={changelog_status!r} "
            f"(a self-consistent narrative is not evidence of fidelity)"
        )

    return {
        "verdict": "PROVENANCE_CONSERVED",
        "consumed": len(marked_consumed),
        "cited": len(cited),
        "in_context_verdict_ignored": changelog_status,
    }
