# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-unverifiable-erase-in-federated-agent-memory-the-tombstone-replay-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-unverifiable-erase-in-federated-agent-memory-the-tombstone-replay-divergence-boundary.warrant.json
# Markdown SHA-256:   6d2e4b934312af94cd24560861957f126075af5104b9ee4daf57a3e5a48207cd
# Code AST SHA-256:   a9b075d64677d9e66b9700a64c55696dc4a3d58cb50a77782422760aa425f899
# Verified Classes:   UnverifiableEraseError, Tombstone, LiveRecord, FederatedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnverifiableEraseError(RuntimeError):
    """Raised when a federated erase proof does not cover live descendants."""


@dataclass
class Tombstone:
    store: str
    revision: int
    predicate: str          # e.g. "doc:D" — tag-based coverage
    signature: str


@dataclass
class LiveRecord:
    store: str
    created_rev: int
    provenance: list[str]   # source tags, may include paraphrased origins
    content_hash: str


@dataclass
class FederatedStore:
    name: str
    current_rev: int
    records: list[LiveRecord] = field(default_factory=list)
    derivation_watermark: int = 0   # last rev at which a derivation job wrote


def verify_erase_proof(
    tombstones: list[Tombstone],
    stores: dict[str, FederatedStore],
) -> dict:
    """
    Enforce descent-closure and monotonic-revision-fence invariants.
    Returns a coverage report or raises UnverifiableEraseError.
    """
    if not tombstones:
        raise UnverifiableEraseError("no tombstones supplied; cannot attest erasure")

    tomb_by_store: dict[str, Tombstone] = {t.store: t for t in tombstones}
    uncovered: list[dict] = []

    for name, store in stores.items():
        tomb = tomb_by_store.get(name)
        if tomb is None:
            uncovered.append({"store": name, "reason": "no tombstone for store"})
            continue

        # Invariant 1: derivation quiescence — no derivation ran past the tombstone.
        if store.derivation_watermark > tomb.revision:
            uncovered.append({
                "store": name,
                "reason": "derivation_watermark exceeds tombstone revision",
                "watermark": store.derivation_watermark,
                "tombstone_rev": tomb.revision,
            })

        # Invariant 2: descent closure — no live record descended from the predicate.
        for rec in store.records:
            descended = any(tomb.predicate in p for p in rec.provenance)
            if descended and rec.created_rev > tomb.revision:
                uncovered.append({
                    "store": name,
                    "reason": "live descendant written after tombstone",
                    "record_hash": rec.content_hash,
                    "created_rev": rec.created_rev,
                    "tombstone_rev": tomb.revision,
                })

    if uncovered:
        raise UnverifiableEraseError(
            f"erase unverifiable: {len(uncovered)} uncovered window(s): {uncovered}"
        )

    proof_digest = hashlib.sha256(
        "".join(f"{t.store}:{t.revision}:{t.signature}" for t in tombstones).encode()
    ).hexdigest()
    return {"erased": True, "coverage": "descent-closed", "proof_digest": proof_digest}


# --- Reproduction of the observed failure ---
if __name__ == "__main__":
    stores = {
        "episodic": FederatedStore(name="episodic", current_rev=4419,
                                   derivation_watermark=0),
        "vec": FederatedStore(name="vec", current_rev=4419,
                              derivation_watermark=0),
        "sem": FederatedStore(
            name="sem", current_rev=4419, derivation_watermark=4415,
            records=[LiveRecord(store="sem", created_rev=4415,
                                provenance=["doc:D", "paraphrase:4402"],
                                content_hash="S_x")],
        ),
    }
    tombstones = [
        Tombstone("episodic", 4410, "doc:D", "sig_ep"),
        Tombstone("vec", 4410, "doc:D", "sig_vec"),
        Tombstone("sem", 4411, "doc:D", "sig_sem"),
    ]
    try:
        verify_erase_proof(tombstones, stores)
    except UnverifiableEraseError as e:
        print(f"REJECTED: {e}")
