# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-that-its-own-provenance-graph-cannot-certify.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-that-its-own-provenance-graph-cannot-certify.warrant.json
# Markdown SHA-256:   738c60af8f5a29f84379e984c640763187d9921446b337ba0c8219a695bca2d5
# Code AST SHA-256:   c5866bf4f19b89e367982d5ff5ed5e8e79887e5b79494327276910a582abc66e
# Verified Classes:   ProvenanceClosureError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceClosureError(RuntimeError):
    """Raised when a scoped forget() cannot certify erasure because the
    provenance graph has unresolvable or missing derivation edges."""
    pass


def scoped_forget(store, scope: str, selector: str = "any") -> dict:
    targets = store.match(scope=scope, selector=selector)

    # P1/P2: closure must be traversable over records, blobs, and vector payloads.
    blocked = []
    for rec in targets:
        for edge in store.out_edges(rec.id, kinds=("summarized_into", "embedded_into", "paraphrase_of")):
            if edge.missing_source or not store.can_traverse(edge.dst):
                blocked.append({"record": rec.id, "edge": edge.kind, "dst": edge.dst})

    # Subjects may survive under foreign keys via fuzzy paraphrase nodes.
    for cand in store.fuzzy_subject_hits(scope):
        if not store.has_derived_from_path(cand.id, targets):
            blocked.append({"record": cand.id, "edge": "paraphrase_of", "dst": "unlinked"})

    # Opaque checkpoints embedding target text are part of the closure.
    for cp in store.checkpoints_containing([r.id for r in targets]):
        if not cp.manifest_covers([r.id for r in targets]):
            blocked.append({"record": cp.id, "edge": "checkpoint_blob", "dst": "opaque"})

    if blocked:
        # Refuse: partial delete under a broken graph destroys the audit trail.
        raise ProvenanceClosureError(
            f"refusing forget(scope={scope!r}): {len(blocked)} unresolvable "
            f"derivations; escalate with blocked set, do not delete"
        )

    deleted = store.delete(targets)
    return {"deleted": deleted, "closure_complete": True}
