# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-forget-as-a-tombstone-obligation-rather-than-a-deletion-when-retention-policy-and-retrieval-index-di.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-forget-as-a-tombstone-obligation-rather-than-a-deletion-when-retention-policy-and-retrieval-index-di.warrant.json
# Markdown SHA-256:   c73e61b8af676dc63a2cb7f4df3c6cb1ac9b6f493f7ffdde7242adb84d20877d
# Code AST SHA-256:   e9274388a5a954631928e1edc4e6a0a50367db0f35252afbb159707f26e25985
# Verified Classes:   GhostMemoryError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GhostMemoryError(RuntimeError):
    """Raised when a forgotten scope still resolves via the retrieval index."""


def forget_and_verify(memory, scope: str, probe_query: str = "*") -> None:
    """
    Discharge the tombstone obligation for a scoped forget.
    Raises GhostMemoryError if any index-resident reference survives.
    """
    result = memory.forget(scope=scope)
    if result.get("status") != "ok":
        raise GhostMemoryError(f"forget() did not acknowledge scope {scope!r}: {result}")

    # Phase two: probe for index-resident ghosts under the forgotten scope
    # and any descendant scopes that share the index's tag namespace.
    survivors = memory.read(
        query=probe_query,
        scope=scope,
        include_tombstones=True,
        exact_scope=True,
    )
    if survivors:
        ids = [s.get("id") for s in survivors]
        raise GhostMemoryError(
            f"scope {scope!r} reported forgotten but index still resolves "
            f"{len(survivors)} record(s): {ids}. "
            f"Index tag namespace likely diverges from deletion predicate; "
            f"issue scoped forget against index tag or write explicit tombstone."
        )


def handoff_after_forget(memory, scope: str, peer) -> None:
    """Hand off a scope to a peer instance only after tombstone verification."""
    forget_and_verify(memory, scope)
    peer.receive_scope(scope, ghost_risk=False)
