# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-tombstone-write-rather-than-a-row-delete-when-agent-memory-carries-provenance-edges.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-forget-as-a-tombstone-write-rather-than-a-row-delete-when-agent-memory-carries-provenance-edges.warrant.json
# Markdown SHA-256:   3213b78cecbb26379f23a193d34d21c65729de0ca32e272362629154aeddb94f
# Code AST SHA-256:   6cb5091734f1fab39f4c0ec57a2bd09349c76b904732dd440bfdc82a5b13ea15
# Verified Classes:   ProvenanceViolation, RedactionIncomplete, NodeState, MemoryNode, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a forget operation would orphan a live provenance edge."""
    pass


class RedactionIncomplete(RuntimeError):
    """Raised when content attributable to a forgotten record survives in a descendant."""
    pass


class NodeState(str, Enum):
    LIVE = "live"
    TOMBSTONED = "tombstoned"
    ABSENT = "absent"


@dataclass
class MemoryNode:
    id: str
    content: str
    state: NodeState = NodeState.LIVE
    derived_from: list[str] = field(default_factory=list)
    derived_to: list[str] = field(default_factory=list)


@dataclass
class ProvenanceStore:
    nodes: dict[str, MemoryNode] = field(default_factory=dict)
    redaction_threshold: float = 0.82

    def inbound(self, target_id: str) -> list[str]:
        return [n.id for n in self.nodes.values()
                if target_id in n.derived_from and n.state == NodeState.LIVE]

    def outbound(self, target_id: str) -> list[str]:
        node = self.nodes.get(target_id)
        if node is None:
            return []
        return [d for d in node.derived_to if self.nodes.get(d, None)
                and self.nodes[d].state == NodeState.LIVE]

    def content_hits(self, target: MemoryNode) -> list[str]:
        # Simplified substring stand-in for the real embedding/span scan.
        needle = target.content.strip()
        if not needle:
            return []
        hits = []
        for n in self.nodes.values():
            if n.id == target.id or n.state != NodeState.LIVE:
                continue
            if needle in n.content:
                hits.append(n.id)
        return hits

    def forget(self, target_id: str) -> str:
        target = self.nodes.get(target_id)
        if target is None:
            raise ProvenanceViolation(f"forget target {target_id} does not exist")

        edges_out = self.outbound(target_id)
        edges_in = self.inbound(target_id)
        hits = self.content_hits(target)

        if not edges_out and not edges_in and not hits:
            # True leaf: physical deletion is contract-valid.
            del self.nodes[target_id]
            return "deleted"

        if edges_out or edges_in:
            # Tombstone instead of delete; do not orphan the graph.
            target.state = NodeState.TOMBSTONED
            target.content = "[REDACTED]"

        if hits:
            # Cascade redaction obligation to every surviving descendant.
            for hit_id in hits:
                descendant = self.nodes[hit_id]
                if target.content not in descendant.content and \
                        target.content.strip() and target.content.strip() in descendant.content:
                    descendant.content = descendant.content.replace(
                        target.content.strip(), "[REDACTED]"
                    )
            # Verify the cascade actually closed the leak.
            residual = [h for h in hits
                        if target.content.strip() and target.content.strip()
                        in self.nodes[h].content]
            if residual:
                raise RedactionIncomplete(
                    f"redaction cascade incomplete for {target_id}; "
                    f"surviving spans in {residual}"
                )

        return "tombstoned_with_redaction"
