# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-erasure-request-has-silently-failed-to-propagate-to-derived-memory-in-an-agent-s-write-path.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-erasure-request-has-silently-failed-to-propagate-to-derived-memory-in-an-agent-s-write-path.warrant.json
# Markdown SHA-256:   545f8e9344c4d6f881f8e496a316022fa0a8d6d789835d91aaaa98fffd752957
# Code AST SHA-256:   fe8100311b51d4e95d0c07abba9322bfc57e3bf67114846d95ee6b4dc5854b48
# Verified Classes:   ErasureClosureViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ErasureClosureViolation(RuntimeError):
    """Raised when a scoped forget reports success but derived records survive."""
    pass


def scoped_forget(store, selector, subject_token):
    """
    Two-phase scoped erasure with closure verification.

    store: object exposing
        .match(selector) -> list[record_id]          # direct hits
        .forward_cone(record_ids) -> set[record_id]  # transitive derived_from
        .subjects_of(record_id) -> set[str]
        .delete(record_id)
        .redact(record_id, drop_subjects)
        .scan_token(token) -> list[record_id]
    """
    # Phase 1: PLAN. Must read the forward cone BEFORE any deletion,
    # because cascade-delete of edges destroys the pointers we need.
    direct = set(store.match(selector))
    cone = store.forward_cone(direct)
    derived = cone - direct

    plan = {"delete": set(direct), "redact": {}, "keep": set()}
    for rid in derived:
        subj = store.subjects_of(rid)
        if subj <= {subject_token}:
            plan["delete"].add(rid)              # fully within scope
        elif subject_token in subj:
            plan["redact"][rid] = {subject_token}  # shared; strip token only
        else:
            plan["keep"].add(rid)                # disjoint; leave alone

    if not plan["delete"] and not plan["redact"]:
        # No-op erasure is suspicious if the token is known to exist.
        if store.scan_token(subject_token):
            raise ErasureClosureViolation(
                f"selector {selector!r} matched no records but token "
                f"{subject_token!r} is still present; selector is "
                f"under-expressive relative to derivation."
            )
        return {"deleted": 0, "redacted": 0, "status": "noop"}

    # Phase 2: EXECUTE.
    for rid in plan["delete"]:
        store.delete(rid)
    for rid, drop in plan["redact"].items():
        store.redact(rid, drop_subjects=drop)

    # Phase 3: VERIFY. Ground truth is the token scan, not the API's count.
    survivors = store.scan_token(subject_token)
    if survivors:
        raise ErasureClosureViolation(
            f"forget({selector!r}) reported ok but {len(survivors)} record(s) "
            f"still contain {subject_token!r}: {survivors}. "
            f"Do NOT retry the same selector; re-plan against the "
            f"rewritten store."
        )

    return {
        "deleted": len(plan["delete"]),
        "redacted": len(plan["redact"]),
        "kept": len(plan["keep"]),
        "status": "verified",
    }
