# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-forget-semantics-before-consolidation-not-after-the-tombstone-replay-resurrection-boundary-in-compliance-grade-agent-me.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-forget-semantics-before-consolidation-not-after-the-tombstone-replay-resurrection-boundary-in-compliance-grade-agent-me.warrant.json
# Markdown SHA-256:   1ceaceb5986f82fb831fb7192542e31adcbcb39ba737ac05cd04548b652c33b2
# Code AST SHA-256:   8775fa1fa12eadc4f430aaa1ab4c197e2ee5ef9fdba3e5d393e11edcce6df60a
# Verified Classes:   ResurrectionBoundaryError
# Defensive Guards:   3 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

class ResurrectionBoundaryError(RuntimeError):
    """Raised when a derived memory artifact would be promoted despite
    intersecting a live tombstone, or when its provenance cannot be
    resolved well enough to prove it is clean."""


def gate_consolidation(artifact, tombstones, resolve_provenance):
    """
    Enforce forget-semantics at consolidation-time.

    artifact: dict with 'id', 'source_entity_ids' (may be None/incomplete),
              'source_episode_ids'.
    tombstones: dict entity_id -> {'effective_at': ..., 'expires_at': ...}
    resolve_provenance: callable(artifact) -> set[str] | None
        Returns the transitive set of source entity ids, or None if
        provenance is incomplete and cannot be resolved.
    """
    provenance = resolve_provenance(artifact)

    # Fail closed: unverifiable provenance is not "clean".
    if provenance is None:
        raise ResurrectionBoundaryError(
            f"artifact {artifact['id']} has unresolvable provenance; "
            f"cannot prove it is free of erased entities. Quarantine."
        )

    # Enforce tombstone over the full provenance closure, not just
    # the primary source rows (which may already be deleted).
    hit = provenance & set(tombstones.keys())
    if hit:
        raise ResurrectionBoundaryError(
            f"artifact {artifact['id']} derives from tombstoned entities "
            f"{sorted(hit)}; promotion refused (resurrection risk)."
        )

    # Tombstone must outlive every artifact it governs.
    for entity in provenance:
        ts = tombstones.get(entity)
        if ts and ts.get("expires_at") is not None:
            if ts["expires_at"] <= artifact.get("expires_at", ts["expires_at"]):
                raise ResurrectionBoundaryError(
                    f"tombstone for {entity} expires before governed "
                    f"artifact {artifact['id']}; extend tombstone."
                )

    return True  # safe to promote
