# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-audit-forget-tool-compliance-when-erasure-is-verified-only-against-the-live-index-and-not-against-derived-semantic-summaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-audit-forget-tool-compliance-when-erasure-is-verified-only-against-the-live-index-and-not-against-derived-semantic-summaries.warrant.json
# Markdown SHA-256:   09e5db4d1b2d9312100f6abe777ee93825de6326f193f7652ee809797ef694ca
# Code AST SHA-256:   6734969ff6282b45511622d47d8dfea3bace477631055937ead576279b0d292a
# Verified Classes:   ErasureAuditError, Store
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable

PARAPHRASE_THRESHOLD = 0.82


class ErasureAuditError(RuntimeError):
    """Raised when a forget-tool compliance audit cannot certify closure."""


@dataclass
class Store:
    episodic: dict[str, str] = field(default_factory=dict)
    summaries: dict[str, dict] = field(default_factory=dict)  # id -> {"text", "source_ids"}
    reverse_index: dict[str, set[str]] | None = None  # source_id -> {artifact_id}
    derivation_generation: int = 0

    def has_reverse_index(self) -> bool:
        return self.reverse_index is not None


def _similarity(a: str, b: str) -> float:
    # Placeholder for the store's embedding cosine; deterministic for the record.
    sa, sb = set(a.lower().split()), set(b.lower().split())
    if not sa or not sb:
        return 0.0
    return len(sa & sb) / len(sa | sb)


def audit_forget(store: Store, erased_id: str, erased_text: str) -> dict:
    if erased_id in store.episodic:
        raise ErasureAuditError(
            f"referent {erased_id} still resolves in live index; forget tool did not run"
        )

    if not store.has_reverse_index():
        # Cannot enumerate derived artifacts; must fail closed.
        return {
            "verdict": "INDETERMINATE",
            "reason": "no reverse lineage index; closure unprovable",
            "generation": store.derivation_generation,
        }

    candidates = store.reverse_index.get(erased_id, set())
    leaked = []
    for artifact_id in candidates:
        artifact = store.summaries.get(artifact_id)
        if artifact is None:
            continue
        sim = _similarity(erased_text, artifact["text"])
        if sim >= PARAPHRASE_THRESHOLD:
            leaked.append({"artifact": artifact_id, "similarity": round(sim, 3)})

    if leaked:
        raise ErasureAuditError(
            f"closure violation: {len(leaked)} derived artifact(s) still carry "
            f"content of {erased_id}: {leaked}"
        )

    return {
        "verdict": "ERASED",
        "probed_artifacts": len(candidates),
        "generation": store.derivation_generation,
    }


def rederive_with_barrier(store: Store, excluded_ids: Iterable[str]) -> Store:
    excluded = set(excluded_ids)
    for sid, artifact in list(store.summaries.items()):
        if artifact["source_ids"] & excluded:
            del store.summaries[sid]
            for src in artifact["source_ids"]:
                store.reverse_index.get(src, set()).discard(sid)
    store.derivation_generation += 1
    return store


# Demonstration of the observed failure trace.
store = Store(
    episodic={"e_113": "user prefers tea", "e_114": "user works late"},
    summaries={
        "S_44": {
            "text": "user medical condition diabetes diagnosis",
            "source_ids": ["e_112", "e_113", "e_114"],
        }
    },
    reverse_index={
        "e_112": {"S_44"},
        "e_113": {"S_44"},
        "e_114": {"S_44"},
    },
)

try:
    audit_forget(store, "e_112", "user medical condition diabetes diagnosis")
except ErasureAuditError as exc:
    # Expected: referent gone from index, but summary S_44 still leaks it.
    print("audit caught leak:", exc)

store = rederive_with_barrier(store, excluded_ids={"e_112"})
print("post-barrier verdict:", audit_forget(store, "e_112", "user medical condition diabetes diagnosis"))
