# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-agent-has-silently-violated-its-coherence-invariant-during-a-memory-compaction-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-agent-has-silently-violated-its-coherence-invariant-during-a-memory-compaction-pass.warrant.json
# Markdown SHA-256:   3e26cf1b4905e173a208823c56c07d1f2c066d188e11ab441374daafa4b188c0
# Code AST SHA-256:   86dd137c146df2f67f52386cdb828d688398f325b49334d99483c1df41e8e980
# Verified Classes:   CoherenceInvariantViolation, Claim, CompactionPass
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class CoherenceInvariantViolation(RuntimeError):
    """Raised when a compaction pass would evict evidence still needed
    by retained claims, breaking the support-closure invariant."""
    pass


@dataclass
class Claim:
    claim_id: str
    supports: Set[str] = field(default_factory=set)   # span IDs
    derived_from: Set[str] = field(default_factory=set)  # other claim IDs


@dataclass
class CompactionPass:
    retained_claims: Dict[str, Claim]
    evicted_spans: Set[str]
    max_depth: int = 2


def support_closure(claims: Dict[str, Claim], root_ids: Set[str]) -> Set[str]:
    """Transitive set of span IDs any retained claim ultimately depends on."""
    spans: Set[str] = set()
    seen: Set[str] = set()
    stack: List[str] = list(root_ids)
    while stack:
        cid = stack.pop()
        if cid in seen:
            continue
        seen.add(cid)
        claim = claims.get(cid)
        if claim is None:
            continue
        spans |= claim.supports
        stack.extend(claim.derived_from)
    return spans


def audit_pass(p: CompactionPass) -> None:
    closure = support_closure(p.retained_claims, set(p.retained_claims))
    severed = closure & p.evicted_spans
    if severed:
        raise CoherenceInvariantViolation(
            f"compaction would evict {len(severed)} span(s) still in the "
            f"support closure of retained claims: {sorted(severed)}"
        )
    # depth check: any claim whose derivation chain exceeds max_depth
    for cid, claim in p.retained_claims.items():
        depth = _chain_depth(p.retained_claims, cid, set())
        if depth > p.max_depth:
            raise CoherenceInvariantViolation(
                f"claim {cid} at compaction depth {depth} exceeds "
                f"max_depth {p.max_depth}; re-grounding required"
            )


def _chain_depth(claims: Dict[str, Claim], cid: str, seen: Set[str]) -> int:
    if cid in seen:
        return 0
    seen.add(cid)
    claim = claims.get(cid)
    if claim is None or not claim.derived_from:
        return 0
    return 1 + max(_chain_depth(claims, d, seen) for d in claim.derived_from)
