# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-erasure-request-has-silently-failed-to-propagate-to-derived-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-erasure-request-has-silently-failed-to-propagate-to-derived-agent-memory.warrant.json
# Markdown SHA-256:   2a670c05acf59f36a81a60040776b59d46ac38746e911811d80ed046ceee8d38
# Code AST SHA-256:   50a88058481d9160a34058015f19cb0c80f0432f13e55e537e91648664349f2e
# Verified Classes:   ProvenanceClosureViolation, MemoryRecord, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceClosureViolation(RuntimeError):
    """Raised when an erasure cannot be proven to reach all derived state."""


@dataclass
class MemoryRecord:
    id: str
    scope: str
    ttl_days: int
    provenance: list[str] = field(default_factory=list)


class ScopedMemory:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}

    def write(self, rec: MemoryRecord) -> None:
        self._records[rec.id] = rec

    def children(self, source_id: str) -> list[MemoryRecord]:
        return [r for r in self._records.values() if source_id in r.provenance]

    def forget(self, source_id: str) -> dict:
        """Forward-closure erasure. Returns a closure manifest, not a boolean."""
        if source_id not in self._records:
            return {"deleted": 0, "scopes_touched": [], "incomplete": 0}

        reached: set[str] = set()
        frontier = [source_id]
        while frontier:
            cur = frontier.pop()
            for child in self.children(cur):
                if child.id not in reached:
                    reached.add(child.id)
                    frontier.append(child.id)

        source = self._records[source_id]
        scopes = {r.scope for r in self._records.values() if r.id in reached}
        scopes.add(source.scope)

        # Structural signal: any derived record in a touched scope whose
        # provenance arity is less than the number of sources that actually
        # contributed. We cannot see true fan-in, so we flag any derived
        # record with remaining TTL > source TTL as a suspected missing edge.
        incomplete = 0
        for r in self._records.values():
            if r.scope in scopes and r.id != source_id:
                if r.ttl_days > source.ttl_days and not r.provenance:
                    incomplete += 1

        for rid in reached | {source_id}:
            self._records.pop(rid, None)

        manifest = {
            "deleted": len(reached) + 1,
            "scopes_touched": sorted(scopes),
            "incomplete": incomplete,
        }

        if incomplete > 0:
            raise ProvenanceClosureViolation(
                f"erasure of {source_id!r} left {incomplete} derived record(s) "
                f"in scopes {sorted(scopes)} with no provenance edge and longer "
                f"TTL than source; forward-closure is unsound, escalate to "
                f"reachability erasure"
            )
        return manifest


def audit_erasure(mem: ScopedMemory, source_id: str) -> dict:
    manifest = mem.forget(source_id)
    if not manifest["scopes_touched"]:
        raise ProvenanceClosureViolation(
            f"forget({source_id!r}) reported no scopes touched; erasure unverified"
        )
    return manifest
