# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-delete-acknowledgment-as-a-tombstone-rather-than-an-erasure-and-why-does-the-distinction-break-r.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-delete-acknowledgment-as-a-tombstone-rather-than-an-erasure-and-why-does-the-distinction-break-r.warrant.json
# Markdown SHA-256:   036f3620ad09f089ec3aa7868a777fc1225e0c3d2e00b973537906dcfec5c64f
# Code AST SHA-256:   9f89997456aa56ecc49d101dec16f22bdaddc2184a76f4dc565ef00e31b1e62f
# Verified Classes:   DerivedCopyRetentionViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DerivedCopyRetentionViolation(RuntimeError):
    """Raised when a forget() ack is treated as erasure while derived copies survive."""
    pass


def execute_forget(memory_store, record_id: str, agent_state) -> dict:
    """
    Two-phase forget. Phase 1: tombstone the authoritative record.
    Phase 2: purge derived copies from agent state, or refuse to certify erasure.
    """
    # Phase 1: authoritative tombstone
    ack = memory_store.forget(record_id)
    if ack.get("status") != "deleted":
        raise DerivedCopyRetentionViolation(
            f"store did not tombstone {record_id}: {ack}"
        )

    # Phase 2: derived-copy audit against the agent's own state
    derived_holders = agent_state.find_copies(record_id)
    # derived_holders: list of (holder_kind, holder_id, purgeable: bool)
    unpurgeable = [h for h in derived_holders if not h.purgeable]

    for holder in derived_holders:
        if holder.purgeable:
            agent_state.purge(holder)
        else:
            # cannot rewrite an append-only log or an already-emitted summary
            pass

    if unpurgeable:
        # Tombstone semantics: authoritative copy gone, derived copies remain.
        # Must NOT claim erasure.
        raise DerivedCopyRetentionViolation(
            f"forget({record_id}) is a tombstone, not an erasure: "
            f"{len(unpurgeable)} derived holder(s) survive and cannot be purged: "
            f"{[h.holder_id for h in unpurgeable]}. "
            f"Report tombstone status; do not certify deletion."
        )

    return {
        "status": "erased",
        "record_id": record_id,
        "tombstone": ack.get("tombstone"),
        "derived_copies_purged": len(derived_holders),
    }
