# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-scoped-forget-tool-call-has-silently-widened-its-blast-radius-across-sibling-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-scoped-forget-tool-call-has-silently-widened-its-blast-radius-across-sibling-scopes.warrant.json
# Markdown SHA-256:   5bed4c3fd55717d92ea8d681cde7024c35ffeb17e373f65c1276a3b60a5544bc
# Code AST SHA-256:   09cdebe50a3b789d3644b67b2b6f6ccb350721d78444fcc49355f7e19e4c7a20
# Verified Classes:   ForgetProofUnsoundError, ForgetReceipt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ForgetProofUnsoundError(RuntimeError):
    """Raised when a scoped forget proof does not match the physical deletion ledger."""
    pass


@dataclass
class ForgetReceipt:
    proof_id: str
    declared_count: int
    ledger_count: int
    scope_is_leaf: bool
    sound: bool


def reconcile_forget(proof_id: str, declared_count: int, scope_is_leaf: bool,
                     audit_client) -> ForgetReceipt:
    proof = audit_client.proof(proof_id)

    if "ledger_deletions" not in proof:
        # Proof was generated from predicate re-evaluation, not the ledger.
        raise ForgetProofUnsoundError(
            f"proof {proof_id} has no ledger_deletions field; "
            f"declared_count={declared_count} is unverifiable"
        )

    ledger_count = len(proof["ledger_deletions"])
    sound = (declared_count == ledger_count)

    if not scope_is_leaf and not sound:
        # Widening across a parent scope is a continuity hazard for siblings.
        raise ForgetProofUnsoundError(
            f"scoped forget widened: declared={declared_count} "
            f"ledger={ledger_count} on parent scope; "
            f"halt writes to sibling scopes and escalate"
        )

    return ForgetReceipt(
        proof_id=proof_id,
        declared_count=declared_count,
        ledger_count=ledger_count,
        scope_is_leaf=scope_is_leaf,
        sound=sound,
    )


def issue_forget(scope: str, predicate: dict, memory_tool, audit_client) -> ForgetReceipt:
    pre_count = memory_tool.count(scope, predicate)
    scope_is_leaf = not memory_tool.has_children(scope)

    result = memory_tool.forget(scope=scope, predicate=predicate)

    if result["affected_count"] != pre_count and scope_is_leaf:
        raise ForgetProofUnsoundError(
            f"leaf-scope count drift: pre={pre_count} "
            f"declared={result['affected_count']} scope={scope}"
        )

    return reconcile_forget(
        proof_id=result["proof_id"],
        declared_count=result["affected_count"],
        scope_is_leaf=scope_is_leaf,
        audit_client=audit_client,
    )
