# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-re-materialized-by-semantic-distillation-after-scoped-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-has-been-re-materialized-by-semantic-distillation-after-scoped-erasure.warrant.json
# Markdown SHA-256:   1aa886048ddfa8bbcf6df6f730177ddf4d1b323d82275ffcd666dde94d1bfb14
# Code AST SHA-256:   d5f7b019ae7fa14284ba89d28116d23b7017c528b9effffb8b27b996ef9efd93
# Verified Classes:   ErasureReMaterializationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ErasureReMaterializationError(RuntimeError):
    """Raised when a semantic node reconstructs tombstoned content without a lineage edge to the tombstone."""
    pass


def verify_erasure_closure(
    semantic_node: dict,
    episodic_index: dict,
    tombstone_ids: set,
    tombstone_scopes: set,
) -> None:
    """
    Enforce the output-side tombstone invariant for a distillation result.

    semantic_node: {"id": str, "text": str, "sources": list[str], "scope": str}
    episodic_index: {episodic_id: {"text": str, "scope": str}}
    tombstone_ids: set of erased episodic IDs
    tombstone_scopes: set of scopes under which erasure was requested

    Raises ErasureReMaterializationError if the node is a derivative of
    erased material, whether by direct lineage or by scope-wide closure.
    """
    sources = semantic_node.get("sources") or []

    # Condition 1: lineage completeness. An empty source set on a summary
    # is a re-materialization vector by construction.
    if not sources:
        raise ErasureReMaterializationError(
            f"semantic node {semantic_node['id']} has no lineage; "
            f"cannot prove it is tombstone-free"
        )

    # Condition 2: direct lineage into a tombstoned episodic record.
    direct_hits = tombstone_ids.intersection(sources)
    if direct_hits:
        raise ErasureReMaterializationError(
            f"semantic node {semantic_node['id']} descends from erased "
            f"records {sorted(direct_hits)}"
        )

    # Condition 3: scope-wide closure. If any source was written under a
    # scope that has since been erased, the derivative is tainted even
    # though the specific source ID was never named in a forget call.
    tainted_scopes = {
        episodic_index[s]["scope"]
        for s in sources
        if s in episodic_index and episodic_index[s]["scope"] in tombstone_scopes
    }
    if tainted_scopes:
        raise ErasureReMaterializationError(
            f"semantic node {semantic_node['id']} draws on sources under "
            f"erased scopes {sorted(tainted_scopes)}; quarantine for "
            f"re-distillation with erased material excluded"
        )


def distill_and_commit(cluster: list[dict], store, tombstones) -> dict:
    node = store.summarize(cluster)
    try:
        verify_erasure_closure(
            node,
            episodic_index=store.episodic_index(),
            tombstone_ids=tombstones.ids(),
            tombstone_scopes=tombstones.scopes(),
        )
    except ErasureReMaterializationError:
        store.quarantine(cluster, reason="tombstone_closure_violation")
        raise
    store.commit_semantic(node)
    return node
