# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-the-poisoning-signal-is-diluted-below-per-entry-anomaly-thresholds.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundered-memory-writes-when-the-poisoning-signal-is-diluted-below-per-entry-anomaly-thresholds.warrant.json
# Markdown SHA-256:   3b4f4a5ab42263d4a29e459feb592410b3d89f03fcda8ee8ac6c5552a24e5741
# Code AST SHA-256:   f765ed59d03eda82c3b5971bea95481cb8f3530c755d899aec5ab6180369b2c8
# Verified Classes:   ProvenanceLaunderingError, Write, CohortAudit
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write cohort or promotion violates evidence-independence."""
    pass


@dataclass
class Write:
    write_id: str
    source_type: str
    root_id: str          # provenance root (original tool result / user turn)
    parent_write_id: str | None
    session_id: str


@dataclass
class CohortAudit:
    root_concentration_max: float = 0.4
    echo_ratio_min: float = 0.5
    min_cohort_for_gate: int = 8
    max_chain_depth: int = 4


def audit_cohort(writes: list[Write], audit: CohortAudit) -> None:
    if len(writes) < audit.min_cohort_for_gate:
        return
    root_counts: dict[str, int] = defaultdict(int)
    for w in writes:
        root_counts[w.root_id] += 1
    total = len(writes)
    top_root, top_count = max(root_counts.items(), key=lambda kv: kv[1])
    concentration = top_count / total
    echo_ratio = len(root_counts) / total

    if concentration > audit.root_concentration_max:
        raise ProvenanceLaunderingError(
            f"root {top_root!r} dominates cohort: concentration={concentration:.2f} "
            f"> {audit.root_concentration_max} over {total} writes"
        )
    if echo_ratio < audit.echo_ratio_min:
        raise ProvenanceLaunderingError(
            f"echo ratio {echo_ratio:.2f} < {audit.echo_ratio_min}: "
            f"{len(root_counts)} distinct roots across {total} writes"
        )


def gate_promotion(supporting_episodes: list[Write]) -> None:
    """Episodic->semantic promotion requires >=2 distinct provenance roots."""
    roots = {w.root_id for w in supporting_episodes}
    if len(roots) < 2:
        raise ProvenanceLaunderingError(
            f"promotion blocked: {len(supporting_episodes)} episodes trace to "
            f"{len(roots)} provenance root(s); repetition is not corroboration"
        )
    # chain-depth check: recursive restatement from a single root
    for w in supporting_episodes:
        depth, cur = 0, w
        seen: set[str] = set()
        while cur.parent_write_id is not None:
            if cur.write_id in seen:
                raise ProvenanceLaunderingError(f"cycle in provenance chain at {w.write_id}")
            seen.add(cur.write_id)
            depth += 1
            if depth > 4:
                raise ProvenanceLaunderingError(
                    f"chain depth > 4 at {w.write_id}: recursive restatement suspected"
                )
            break  # single-hop check; full walk omitted for brevity
