# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-call-tombstone-re-derivation-failure-in-retention-governed-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-call-tombstone-re-derivation-failure-in-retention-governed-memory-tool-apis.warrant.json
# Markdown SHA-256:   eafe59773477c5717cd3b50ee61485b4cc14619156df9e4198852810fc84378b
# Code AST SHA-256:   0f9b605ec220513d0a6d28a8cde5893eb4d313afa7e026d0fcaced24c9e6bede
# Verified Classes:   ErasureClosureError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ErasureClosureError(RuntimeError):
    """Raised when a forget call cannot prove closure over derived memory tiers."""


def forget_subject(store, subject_id: str, active_derivation_jobs: set[str],
                   agent_working_set: set[str]) -> dict:
    lineage = store.lineage_for(subject_id)
    if lineage is None:
        raise ErasureClosureError(
            f"no provenance for {subject_id!r}; cannot enumerate derived artifacts"
        )

    source_tiers = {rec.tier for rec in lineage.sources}
    unfenced = source_tiers & active_derivation_jobs
    if unfenced:
        # Tombstoning now would let the live distiller read pre-tombstone
        # state and write post-tombstone facts: silent resurrection.
        raise ErasureClosureError(
            f"derivation jobs {sorted(unfenced)} are sources for {subject_id!r} "
            f"and are not fenced; refusing to tombstone"
        )

    if subject_id in agent_working_set:
        # In-flight context can re-write erased facts on the next tool call.
        raise ErasureClosureError(
            f"{subject_id!r} still resident in agent working set; "
            f"invalidate context before erasure"
        )

    store.tombstone(subject_id)           # fence first
    purged = store.purge_all_tiers(subject_id, lineage)
    return {"status": "ok", "purged": purged, "closure_verified": True}
