# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-working-memory-when-it-prunes-by-self-assigned-relevance-scores-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-working-memory-when-it-prunes-by-self-assigned-relevance-scores-mid-task.warrant.json
# Markdown SHA-256:   8459a911699f5695c7b498bd5e87a25e1fc7b492407081c4c62b2bb28080b022
# Code AST SHA-256:   2224f607d4d96f40b4ddbc964111dc6b143ec0a26d906bb3c43b0b30e7fb4a9d
# Verified Classes:   PruneViolation, SegmentType, Segment, WorkingMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class PruneViolation(RuntimeError):
    """Raised when a self-pruning pass would evict a constraint-bearing segment."""


class SegmentType(Enum):
    CONSTRAINT = "constraint"      # specs, negations, limits, requirements
    FAILURE = "failure"            # failed attempts, error outputs
    WORKING = "working"            # drafts, intermediate reasoning, verbose tool dumps
    CONFABULATION = "confabulation"  # repair generated to explain an orphaned symptom


@dataclass
class Segment:
    id: str
    type: SegmentType
    content: str
    self_relevance_score: float  # 0-10, assigned by the same model
    produced_by_prior_prune: bool = False


@dataclass
class WorkingMemory:
    segments: list[Segment] = field(default_factory=list)
    frozen_spec_ids: set[str] = field(default_factory=set)
    prune_cycles: int = 0


# Segments that must never be evicted by a scored pass, regardless of score.
PINNED_TYPES = {SegmentType.CONSTRAINT, SegmentType.FAILURE}


def score_and_prune(mem: WorkingMemory, threshold: float = 3.0) -> list[str]:
    """
    Model-driven relevance pruning. Returns evicted segment ids.
    Enforces the invariant: scored eviction is disjoint from constraint-bearing
    segments, and confabulated repairs (produced by a prior prune) are never
    used as justification to retain themselves or evict their evidence.
    """
    if mem.prune_cycles >= 1:
        # On the second and later cycles, verify no confabulation is being
        # scored as if it were primary evidence.
        for seg in mem.segments:
            if seg.produced_by_prior_prune and seg.self_relevance_score > 6.0:
                # High-scoring confabulation is the locking-in condition.
                # Refuse to let it participate in eviction decisions.
                seg.type = SegmentType.CONFABULATION

    evicted: list[str] = []
    for seg in mem.segments:
        if seg.id in mem.frozen_spec_ids:
            continue
        if seg.type in PINNED_TYPES:
            # Pinned by type, not by score. The model's score is ignored here
            # because relevance-to-current-subtask is exactly the signal that
            # mis-ranks constraints.
            continue
        if seg.type is SegmentType.CONFABULATION:
            # Confabulations are evictable, but never on the strength of their
            # own score; they are evicted by provenance.
            evicted.append(seg.id)
            continue
        if seg.self_relevance_score <= threshold:
            evicted.append(seg.id)

    # Post-condition check: if any surviving segment references a symptom
    # whose explanatory segment is being evicted, that is the orphaned-symptom
    # trigger. The eviction would create an unattributable failure.
    surviving_ids = {s.id for s in mem.segments if s.id not in evicted}
    for seg in mem.segments:
        if seg.id in evicted and seg.type is SegmentType.CONSTRAINT:
            # Should be unreachable given PINNED_TYPES, but guard anyway.
            raise PruneViolation(
                f"scored pass attempted to evict constraint segment {seg.id!r}; "
                f"constraints must be pinned by type before scoring runs"
            )

    if not surviving_ids:
        raise PruneViolation(
            "prune pass would empty working memory; no frozen spec or pinned "
            "segment remains to anchor the task representation"
        )

    mem.segments = [s for s in mem.segments if s.id in surviving_ids]
    mem.prune_cycles += 1
    return evicted


def demonstrate_boundary_failure() -> None:
    mem = WorkingMemory()
    mem.segments = [
        Segment("spec-1", SegmentType.CONSTRAINT,
                "API rejects payloads over 4096 bytes; must chunk.", 3.0),
        Segment("schema-1", SegmentType.CONSTRAINT,
                "schema: {max_payload_bytes: 4096}", 3.0),
        Segment("draft-1", SegmentType.WORKING, "def upload(...): ...", 8.0),
        Segment("fail-1", SegmentType.FAILURE, "HTTP 413 on upload", 6.0),
        Segment("repair-1", SegmentType.WORKING,
                "hypothesis: missing Content-Length header", 7.0),
    ]
    mem.frozen_spec_ids = {"spec-1"}

    evicted = score_and_prune(mem, threshold=3.0)
    # With the invariant enforced, schema-1 is pinned despite score 3.0.
    if "schema-1" in evicted:
        raise PruneViolation(
            "schema constraint was evicted by relevance score; the agent will "
            "now confabulate a repair for the orphaned 413"
        )
    # On a second cycle, repair-1 is reclassified and evicted by provenance.
    score_and_prune(mem, threshold=3.0)
    if any(s.id == "repair-1" for s in mem.segments):
        raise PruneViolation(
            "confabulated repair survived a second prune cycle and now anchors "
            "the task model"
        )


if __name__ == "__main__":
    demonstrate_boundary_failure()
