# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-provenance-scoped-forget-call-that-would-orphan-a-live-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-provenance-scoped-forget-call-that-would-orphan-a-live-derivation.warrant.json
# Markdown SHA-256:   c287eb9dddb49c5d4b17cfd8917688ff624d0b88fb06858d9a4d2bff30d7d693
# Code AST SHA-256:   26c752505c8e56c9f5df3110ebebc02af380e733a46b1a3b47278adcf77a5010
# Verified Classes:   ProvenanceOrphanError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceOrphanError(RuntimeError):
    """Raised when a forget call would leave a live record citing a tombstoned ancestor."""
    pass


def forget(memory, target_id, cascade="refuse"):
    record = memory.get(target_id)
    if record is None:
        return {"ok": True, "noop": True}

    citing = memory.reverse_citations(target_id)  # live records with target_id in derived_from
    superseded_by = record.meta.get("superseded_by")

    if citing and cascade != "demote":
        raise ProvenanceOrphanError(
            f"forget({target_id}) would orphan live records {citing}; "
            f"pass cascade='demote' to proceed atomically."
        )

    for cid in citing:
        held = memory.policy(cid)
        if held.blocks_orphaning:
            raise ProvenanceOrphanError(
                f"policy '{held.name}' on {cid} forbids orphaning via forget({target_id})."
            )

    # atomic phase: demote citers, transfer supersession, then tombstone
    with memory.transaction():
        for cid in citing:
            memory.update(cid, status="unverified", orphaned_by=target_id)
            if superseded_by:
                memory.update(cid, superseded_by=superseded_by)
        memory.tombstone(target_id)
        memory.emit_tombstone_event(target_id, affected=citing)

    return {"ok": True, "demoted": citing, "supersession_transferred": bool(superseded_by)}
