# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-crossing-writes-when-its-memory-tool-s-retention-policy-silently-widens-the-effective-write-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-crossing-writes-when-its-memory-tool-s-retention-policy-silently-widens-the-effective-write-set.warrant.json
# Markdown SHA-256:   e732c07422d9594ebb8b2633fe15f5818017907994efe79dd41ba3261818b82f
# Code AST SHA-256:   0f36880f6cbe65b1637e3c451756c58d77eb226dbcf9267f294d4e087a9ab6fc
# Verified Classes:   ScopeContainmentViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeContainmentViolation(RuntimeError):
    """Raised when a record written under one scope surfaces under another
    after a forget that claimed to erase the origin scope."""
    pass


def forget_with_containment_probe(
    memory,
    scope: str,
    probe_scope: str,
    origin_tag: str,
) -> dict:
    """Issue a scoped forget, then verify no payload leaked into a broader
    scope via tier promotion. Returns the forget receipt on success.

    memory: object exposing .forget(scope) and .read(scope, query).
    Raises ScopeContainmentViolation if the forget is tier-incomplete or
    if a post-forget probe read returns any record tagged with origin_tag.
    """
    receipt = memory.forget(scope=scope)

    # Invariant 2: residual counts must be tier-complete.
    tiers_checked = receipt.get("tiers_checked")
    if tiers_checked is None:
        raise ScopeContainmentViolation(
            f"forget(scope={scope!r}) returned no tier manifest; "
            f"residual={receipt.get('residual')} is unverifiable. "
            f"Containment guarantee downgraded to best-effort."
        )

    # Invariant 1 & 3: probe the broadest reachable scope for leaked payload.
    leaked = memory.read(scope=probe_scope, query=origin_tag)
    if leaked:
        leaked_scopes = {r.get("scope") for r in leaked}
        raise ScopeContainmentViolation(
            f"forget(scope={scope!r}) left {len(leaked)} record(s) reachable "
            f"under probe_scope={probe_scope!r} (origin scopes: {leaked_scopes}). "
            f"Promotion path is not scope-preserving; do not re-forget under "
            f"probe_scope. Escalate to operator."
        )

    return receipt
