# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-incomplete-right-to-erasure-propagation-across-federated-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-incomplete-right-to-erasure-propagation-across-federated-agent-memory-stores.warrant.json
# Markdown SHA-256:   edc25f6a01dfc0ed149458edd3c0b0f031cc026b0f3f6b10f8043eec63e32af4
# Code AST SHA-256:   e34cbf1709cc04f1765dd80d53613ea0cbab0a97e11c6e8ee240d33571d06ed2
# Verified Classes:   ErasureClosureError, Artifact, ErasureCertificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureClosureError(RuntimeError):
    """Raised when an erasure request cannot certify derivation-closure."""
    pass


@dataclass
class Artifact:
    artifact_id: str
    store: str
    roots: frozenset[str]          # complete derivation roots, enforced at write
    lineage_complete: bool = True


@dataclass
class ErasureCertificate:
    target: str
    closure: frozenset[str]
    graph_snapshot_hash: str
    erased: bool
    pending: list[str] = field(default_factory=list)


def compute_closure(target: str, artifacts: list[Artifact]) -> frozenset[str]:
    """Closure under derivation. Any incomplete lineage poisons the result."""
    closure = set()
    for a in artifacts:
        if target in a.roots:
            if not a.lineage_complete:
                # truncated roots: cannot trust membership; closure is unsound
                raise ErasureClosureError(
                    f"artifact {a.artifact_id} in store {a.store} has incomplete "
                    f"lineage; closure over target {target} is unverifiable"
                )
            closure.add(a.artifact_id)
    return frozenset(closure)


def certify_erasure(
    target: str,
    artifacts: list[Artifact],
    reachable_stores: set[str],
    all_stores: set[str],
) -> ErasureCertificate:
    try:
        closure = compute_closure(target, artifacts)
    except ErasureClosureError:
        # conservative sweep required; never report erased=True
        return ErasureCertificate(
            target=target,
            closure=frozenset(),
            graph_snapshot_hash="",
            erased=False,
            pending=sorted(all_stores),
        )

    unreachable = all_stores - reachable_stores
    snapshot = hashlib.sha256(
        repr(sorted((a.artifact_id, tuple(sorted(a.roots))) for a in artifacts)).encode()
    ).hexdigest()

    if unreachable:
        # fail-closed: pending obligations must survive cold start
        return ErasureCertificate(
            target=target,
            closure=closure,
            graph_snapshot_hash=snapshot,
            erased=False,
            pending=sorted(unreachable),
        )

    # verify closure is actually a subset of what we processed
    processed = {a.artifact_id for a in artifacts if a.store in reachable_stores}
    if not closure.issubset(processed):
        raise ErasureClosureError(
            f"closure for {target} contains artifacts outside processed set: "
            f"{closure - processed}"
        )

    return ErasureCertificate(
        target=target,
        closure=closure,
        graph_snapshot_hash=snapshot,
        erased=True,
    )
