# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-provenance-tagged-memory-write-whose-erasure-warrant-cannot-be-satisfied-by-the-forget-api.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-provenance-tagged-memory-write-whose-erasure-warrant-cannot-be-satisfied-by-the-forget-api.warrant.json
# Markdown SHA-256:   a1a0d6d72d1dd4c5d6b3414cfb60abf515d7a35c6355091ce335b1e5a22ce09b
# Code AST SHA-256:   315ca0bf9d4eff8e20a130222e577018a3e2f60bd2385732ff864490fbe54b96
# Verified Classes:   ErasureWarrantDivergence, ToolCapability, SessionManifest, ProvenanceTag
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable


class ErasureWarrantDivergence(RuntimeError):
    """Raised when an erasable write is accepted in a session whose
    transformation tools are not provenance-closed, making a future
    forget(subject_id) unsound."""
    pass


@dataclass(frozen=True)
class ToolCapability:
    name: str
    provenance_preserving: bool


@dataclass
class SessionManifest:
    tools: list[ToolCapability] = field(default_factory=list)

    def non_propagating(self) -> list[str]:
        return [t.name for t in self.tools if not t.provenance_preserving]


@dataclass
class ProvenanceTag:
    subject_id: str
    consent_scope: str
    retention_class: str  # "erasable" | "retain"


def guard_erasable_write(tag: ProvenanceTag, manifest: SessionManifest) -> None:
    """
    Enforce the provenance-closure invariant at write time.

    An erasable write is admissible only if every transformation tool
    reachable in this session propagates the provenance key. A single
    non-propagating tool (summarizer, embedder, handoff writer) poisons
    every erasable write in the session, because the agent cannot predict
    which writes it will later distill.
    """
    if tag.retention_class != "erasable":
        return  # retain-class writes carry no erasure promise

    leaks = manifest.non_propagating()
    if leaks:
        raise ErasureWarrantDivergence(
            f"Refusing erasable write for subject_id={tag.subject_id!r}: "
            f"session contains provenance-blind transformation tools {leaks}. "
            f"A future forget(subject_id={tag.subject_id!r}) cannot enumerate "
            f"derived records produced by these tools, so any 'complete' "
            f"status would be a false attestation. Route to scratchpad or "
            f"downgrade retention_class, or register these tools as "
            f"provenance_preserving before writing."
        )


def forget(subject_id: str, reachable_stores: Iterable[str],
           scanned_stores: Iterable[str]) -> dict:
    """
    Forget is only 'complete' if it scanned every reachable store.
    Otherwise it must report partial and name the blind stores.
    """
    reachable = set(reachable_stores)
    scanned = set(scanned_stores)
    blind = reachable - scanned
    if blind:
        return {"status": "partial", "erased": None, "unscanned": sorted(blind)}
    return {"status": "complete", "erased": None, "residual_untagged": 0}


if __name__ == "__main__":
    # Session exposes a summarizer that drops provenance: erasable write must be refused.
    manifest = SessionManifest(tools=[
        ToolCapability("write", provenance_preserving=True),
        ToolCapability("summarize", provenance_preserving=False),
        ToolCapability("embed", provenance_preserving=True),
    ])
    tag = ProvenanceTag("cust_4471", "support_only", "erasable")
    try:
        guard_erasable_write(tag, manifest)
    except ErasureWarrantDivergence as e:
        print(f"REFUSED: {e}")
