# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-stores-when-the-forget-tool-audit-trail-is-the-only-surviving-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-stores-when-the-forget-tool-audit-trail-is-the-only-surviving-evidence.warrant.json
# Markdown SHA-256:   b05bf3ad1e5a41c19bc84e7d0343874c556bc784adf528506aeac55d75d5edd1
# Code AST SHA-256:   75456e71e13f0fce256691966899464fbb5d576aea1c83224997177742fde1eb
# Verified Classes:   ProvenanceIntegrityError, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ProvenanceIntegrityError(RuntimeError):
    """Raised when a memory's provenance chain is structurally broken by a forget event."""
    pass


@dataclass(frozen=True)
class Tombstone:
    target_id: str
    warrant_ref: Optional[str]      # must be a resolvable reference, not free text
    initiator: str
    seq: int


def audit_forget_trail(
    tombstones: list[Tombstone],
    live_memory_ids: set[str],
    distilled_from: dict[str, list[str]],
) -> list[str]:
    """
    Reconstruct the forget graph and return IDs of live memories whose
    provenance is broken. Raises on a self-warranted (circular) deletion,
    which invalidates the audit trail's authority and must be escalated.
    """
    quarantined: list[str] = []
    tombstoned_ids = {t.target_id for t in tombstones}

    for t in tombstones:
        # Anomaly 3: self-warranted deletion -> circular authority, escalate.
        if t.warrant_ref is not None and t.warrant_ref == t.target_id:
            raise ProvenanceIntegrityError(
                f"circular deletion warrant at seq={t.seq}: "
                f"target {t.target_id!r} warrants its own removal"
            )

    # Anomaly 4: distillation laundering. A live semantic memory whose
    # distilled_from chain terminates in a tombstoned id has unverifiable
    # provenance and must be quarantined, not deleted.
    for mem_id, sources in distilled_from.items():
        if mem_id not in live_memory_ids:
            continue
        broken = [s for s in sources if s in tombstoned_ids]
        if broken:
            quarantined.append(mem_id)

    return quarantined


def enforce_quarantine(quarantined: list[str], retrieval_index: dict) -> None:
    if not quarantined:
        return
    for mem_id in quarantined:
        if mem_id not in retrieval_index:
            raise ProvenanceIntegrityError(
                f"quarantine target {mem_id!r} absent from retrieval index; "
                "audit trail and live store have diverged"
            )
        retrieval_index[mem_id]["quarantined"] = True
        retrieval_index[mem_id]["quarantine_digest"] = hashlib.sha256(
            mem_id.encode()
        ).hexdigest()
