# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-episodic-write-survives-the-forget-tool-audit-trail.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-episodic-write-survives-the-forget-tool-audit-trail.warrant.json
# Markdown SHA-256:   8bf101d16bd8eb1d6fec265b8317aa8286a3518083d15c058cdf9653216b84e5
# Code AST SHA-256:   492e2fa94e906bf7066da65d193c56c4301862fcbb50805e5366d4e9e02de205
# Verified Classes:   ProvenanceClosureError, Artifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceClosureError(RuntimeError):
    """Raised when a forget operation cannot certify that influence has ceased."""


@dataclass
class Artifact:
    artifact_id: str
    kind: str                      # "episodic" | "semantic" | "exemplar" | "cache"
    source_ids: set[str] = field(default_factory=set)
    tainted: bool = False
    tombstoned: bool = False


def certify_forget_closure(
    target_id: str,
    artifacts: dict[str, Artifact],
    episodic_derivation_index: dict[str, set[str]],
    semantic_provenance_index: dict[str, set[str]],
) -> set[str]:
    """Traverse the union derivation graph from target_id and certify closure.

    Returns the set of artifact IDs that were traversed and are now dead
    (tombstoned or re-derived clean). Raises ProvenanceClosureError if any
    reachable artifact is live, tainted, or unprovable.
    """
    # Step 1: reconcile the two indexes. A record present in one and absent
    # in the other is a closure gap -- deletion and forgetting have diverged.
    all_ids = set(episodic_derivation_index) | set(semantic_provenance_index)
    gaps = {
        i for i in all_ids
        if episodic_derivation_index.get(i, set())
        != semantic_provenance_index.get(i, set())
    }
    if gaps:
        raise ProvenanceClosureError(
            f"closure gap: derivation indexes disagree on {sorted(gaps)}; "
            f"cannot certify forget for {target_id}"
        )

    # Step 2: BFS over the union derivation graph.
    reachable: set[str] = set()
    frontier: list[str] = [target_id]
    while frontier:
        current = frontier.pop()
        if current in reachable:
            continue
        reachable.add(current)
        for child in episodic_derivation_index.get(current, set()) | \
                     semantic_provenance_index.get(current, set()):
            frontier.append(child)

    # Step 3: every reachable artifact must be dead or verified clean.
    live_violations: list[str] = []
    for aid in reachable:
        art = artifacts.get(aid)
        if art is None:
            raise ProvenanceClosureError(
                f"reachable artifact {aid} absent from store; "
                f"provenance unprovable for {target_id}"
            )
        if art.kind == "exemplar" and not art.tombstoned:
            raise ProvenanceClosureError(
                f"reachable exemplar {aid} still live; template invalidation "
                f"required before forget of {target_id} can close"
            )
        if art.tainted and not art.tombstoned:
            live_violations.append(aid)

    if live_violations:
        raise ProvenanceClosureError(
            f"forget of {target_id} incomplete: tainted artifacts still live: "
            f"{sorted(live_violations)}; quarantine and re-derive from clean sources"
        )

    return reachable
