# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-acknowledge-a-cross-org-erasure-proof-it-cannot-cryptographically-verify-the-consent-binding-gap-in-federated-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-acknowledge-a-cross-org-erasure-proof-it-cannot-cryptographically-verify-the-consent-binding-gap-in-federated-agent-memory.warrant.json
# Markdown SHA-256:   75ee13b3817d42c675b9270eb14cf0f07f36c3fe66ae1ea21af368d24e9e15eb
# Code AST SHA-256:   b32f416f40a87764842fa90a8d8f6e90b97112e19c4484fd7c0aa71075002113
# Verified Classes:   ErasureWarrantError, EntryClass, MemoryEntry, ErasureProof, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ErasureWarrantError(RuntimeError):
    """Raised when a consumer agent cannot substantiate the erasure warrant it is about to issue."""


class EntryClass(Enum):
    DERIVED = "derived"      # distilled directly from ingested blobs
    INFERRED = "inferred"    # self-authored reasoning over ingested content


@dataclass
class MemoryEntry:
    entry_id: str
    entry_class: EntryClass
    derivation_set: frozenset[str]   # union of ALL source blob hashes, not a single back-pointer
    premise_set: frozenset[str] = field(default_factory=frozenset)  # for INFERRED entries


@dataclass
class ErasureProof:
    subject_id: str
    blob_hashes: frozenset[str]
    epoch: int
    signature_valid: bool


@dataclass
class Warrant:
    full: bool
    erased_derivations: frozenset[str]
    suppressed_inferences: frozenset[str]
    unresolved_suspects: frozenset[str]


def issue_erasure_warrant(
    proof: ErasureProof,
    entries: list[MemoryEntry],
    last_ingest_epoch: int,
) -> Warrant:
    if not proof.signature_valid:
        raise ErasureWarrantError(f"proof for {proof.subject_id} failed signature check")

    # Stale/replayed proof guard: never tombstone state newer than the proof.
    if proof.epoch < last_ingest_epoch:
        raise ErasureWarrantError(
            f"proof epoch {proof.epoch} predates last ingest {last_ingest_epoch}; "
            "refusing to tombstone current state on a stale proof"
        )

    erased: set[str] = set()
    suppressed: set[str] = set()
    suspects: set[str] = set()

    for e in entries:
        if e.entry_class is EntryClass.DERIVED:
            if e.derivation_set <= proof.blob_hashes:
                erased.add(e.entry_id)
            elif e.derivation_set & proof.blob_hashes:
                # merged entry: partial overlap means closure is NOT established
                suspects.add(e.entry_id)
        else:  # INFERRED
            if e.premise_set & proof.blob_hashes:
                suppressed.add(e.entry_id)

    if suspects:
        # Cannot claim full erasure while any derived entry shares erased derivation.
        raise ErasureWarrantError(
            f"closure not established for {proof.subject_id}: "
            f"{len(suspects)} derived entries share erased derivation but are not fully covered; "
            "issue a partial warrant, not a full one"
        )

    full = not suppressed
    return Warrant(
        full=full,
        erased_derivations=frozenset(erased),
        suppressed_inferences=frozenset(suppressed),
        unresolved_suspects=frozenset(),
    )
