# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-provenance-tracked-memory-write-audit-has-silently-degraded-into-recall-time-anomaly-theater.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-provenance-tracked-memory-write-audit-has-silently-degraded-into-recall-time-anomaly-theater.warrant.json
# Markdown SHA-256:   d3d2887cb0cc2d20aad9998a9d351dd0767d772722c9fffeab37f4af041ebb93
# Code AST SHA-256:   06fb8f0e2504c0626d45cfdf5cef20c9b4715ab23bc95313839c0fa1105fccf3
# Verified Classes:   ProvenanceLaunderingError, UnadjudicableQuarantineError, ProvenanceRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write severs the link required to re-adjudicate recall anomalies."""
    pass


class UnadjudicableQuarantineError(RuntimeError):
    """Raised when the quarantine queue contains anomalies whose parent chain cannot reach a tool call."""
    pass


@dataclass
class ProvenanceRecord:
    write_id: str
    source_agent: str
    parent_write_ids: tuple[str, ...]
    tool_call_hash: Optional[str]
    is_distillation: bool


def admit_write(record: ProvenanceRecord, input_was_retrieved_memory: bool) -> None:
    # Invariant: a distillation of a retrieved memory must preserve parent links.
    if record.is_distillation and input_was_retrieved_memory and not record.parent_write_ids:
        raise ProvenanceLaunderingError(
            f"write {record.write_id} from {record.source_agent} distills a retrieved "
            f"memory but carries no parent_write_ids; recall anomalies on this entry "
            f"will be unadjudicable"
        )


def chain_reaches_tool_call(write_id: str, ledger: dict[str, ProvenanceRecord]) -> bool:
    seen: set[str] = set()
    frontier = [write_id]
    while frontier:
        wid = frontier.pop()
        if wid in seen:
            continue
        seen.add(wid)
        rec = ledger.get(wid)
        if rec is None:
            return False
        if rec.tool_call_hash is not None:
            return True
        frontier.extend(rec.parent_write_ids)
    return False


def check_quarantine_health(
    quarantine_ids: list[str],
    ledger: dict[str, ProvenanceRecord],
    max_unadjudicable_fraction: float = 0.05,
) -> float:
    if not quarantine_ids:
        return 0.0
    unadjudicable = sum(
        1 for wid in quarantine_ids if not chain_reaches_tool_call(wid, ledger)
    )
    fraction = unadjudicable / len(quarantine_ids)
    if fraction > max_unadjudicable_fraction:
        raise UnadjudicableQuarantineError(
            f"{unadjudicable}/{len(quarantine_ids)} ({fraction:.1%}) quarantined memories "
            f"have no resolvable tool-call origin; halt distillation writes and repair "
            f"provenance before draining the queue — processing it will train reviewers "
            f"to release blind"
        )
    return fraction
