# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-pruning-of-its-own-reasoning-traces-has-crossed-from-compaction-into-semantic-amnesia.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-pruning-of-its-own-reasoning-traces-has-crossed-from-compaction-into-semantic-amnesia.warrant.json
# Markdown SHA-256:   fb4a49483ea43f83b168bd25ae8eca6862c870cbf4e0f3f54bff6b427469180c
# Code AST SHA-256:   11321ec20da43b712cb6e08ba7f5e1758d2d46ea61a5f0568b190d248e779d00
# Verified Classes:   AmnesicPruneError, Trace, ContextPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class AmnesicPruneError(RuntimeError):
    """Raised when a prune would delete the sole anchor of a live invariant."""


@dataclass
class Trace:
    tid: str
    stale: bool
    anchors: Set[str] = field(default_factory=set)  # invariants this trace roots


class ContextPolicy:
    def __init__(self) -> None:
        self.traces: Dict[str, Trace] = {}
        self.live_invariants: Set[str] = set()

    def anchor_count(self, invariant: str) -> int:
        return sum(1 for t in self.traces.values() if invariant in t.anchors)

    def prune(self, tid: str) -> None:
        t = self.traces[tid]
        if not t.stale:
            return  # not even a candidate
        for inv in t.anchors:
            if inv in self.live_invariants and self.anchor_count(inv) <= 1:
                raise AmnesicPruneError(
                    f"prune of {tid!r} would orphan live invariant {inv!r}; "
                    f"rewrite-in-place required, not deletion"
                )
        del self.traces[tid]

    def prune_rate_exceeds_growth(self, pruned: int, new_state: int) -> bool:
        return pruned > new_state


def self_edit_cycle(policy: ContextPolicy, candidates: list[str], new_state: int) -> int:
    pruned = 0
    for tid in candidates:
        try:
            policy.prune(tid)
            pruned += 1
        except AmnesicPruneError:
            # downgrade to rewrite: keep the anchor, strip stale payload
            continue
    if policy.prune_rate_exceeds_growth(pruned, new_state):
        raise AmnesicPruneError(
            f"prune rate {pruned} exceeds new-state growth {new_state}: "
            "policy is consuming history faster than it produces replacements"
        )
    return pruned
