# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-forgetting-tool-call-has-silently-failed-to-enforce-deletion-across-an-agent-s-memory-substrate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-forgetting-tool-call-has-silently-failed-to-enforce-deletion-across-an-agent-s-memory-substrate.warrant.json
# Markdown SHA-256:   ac000e4a480fe48162cdb21e983885d7d7429fc83397ef7db984c1f1d565b3c2
# Code AST SHA-256:   99e1e41f3f327a5aa19de284e83b0986d5787d70c1ccf1dd0a67a65f8d46dee0
# Verified Classes:   ForgettingEnforcementError, MemorySubstrate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class ForgettingEnforcementError(RuntimeError):
    """Raised when a forget call returns success but substrate state shows the content survived."""
    pass


@dataclass
class MemorySubstrate:
    vector_store: dict = field(default_factory=dict)   # id -> content
    summary_store: dict = field(default_factory=dict)  # id -> content
    tombstones: set = field(default_factory=set)       # content hashes
    distillation_cadence_s: float = 90.0

    def _hash(self, text: str) -> str:
        return hashlib.sha256(text.strip().lower().encode()).hexdigest()

    def forget(self, memory_id: str) -> dict:
        content = self.vector_store.pop(memory_id, None)
        if content is None:
            return {"status": "not_found", "memory_id": memory_id}
        self.tombstones.add(self._hash(content))
        # NOTE: summary_store is NOT purged here — this is the bug being guarded against.
        return {"status": "ok", "memory_id": memory_id}

    def distillation_pass(self, sibling_id: str, sibling_content: str) -> None:
        # Re-derives a summary from a sibling; may resurrect forgotten content.
        derived = f"Summary: {sibling_content}"
        new_id = f"mem_{len(self.summary_store) + 5000}"
        self.summary_store[new_id] = derived

    def content_probe(self, needle: str) -> list:
        h = self._hash(needle)
        hits = []
        for mid, text in {**self.vector_store, **self.summary_store}.items():
            if self._hash(text) == h or needle.lower() in text.lower():
                hits.append(mid)
        return hits


def forget_and_verify(substrate: MemorySubstrate, memory_id: str,
                      forgotten_text: str, sibling_id: str,
                      sibling_content: str) -> None:
    result = substrate.forget(memory_id)
    if result["status"] != "ok":
        raise ForgettingEnforcementError(f"forget did not commit for {memory_id}: {result}")

    # Simulate one distillation cycle that could re-derive the content.
    substrate.distillation_pass(sibling_id, sibling_content)
    time.sleep(0)  # cadence elapse modeled as immediate in test

    survivors = substrate.content_probe(forgotten_text)
    if survivors:
        raise ForgettingEnforcementError(
            f"forget for {memory_id} returned ok but content survived in {survivors}; "
            f"resurrection by re-derivation — tombstone hash {substrate._hash(forgotten_text)[:12]} "
            f"was not enforced against distillation output"
        )


# Demonstrates the failure: sibling content contains the forgotten address.
sub = MemorySubstrate(vector_store={"mem_4471": "ship to 44 Elm St"})
forget_and_verify(
    sub,
    memory_id="mem_4471",
    forgotten_text="44 Elm St",
    sibling_id="mem_4400",
    sibling_content="Customer prefers deliveries to 44 Elm St, weekday mornings.",
)
