# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-self-editing-context-policies-have-crossed-a-prompt-budget-reallocation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-self-editing-context-policies-have-crossed-a-prompt-budget-reallocation-invariant.warrant.json
# Markdown SHA-256:   d6c6228c7a9f437b2275721410bbd83dc68469a0dcd0dfd8e903c7f8eb429e22
# Code AST SHA-256:   19be05f77ac7095278b5b8ba67ac4aa9f8813e054c38a81b1a4c4929a0eac444
# Verified Classes:   ContextInvariantError, Segment, PolicyState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ContextInvariantError(RuntimeError):
    """Raised when a self-edit would violate a prompt budget reallocation invariant."""
    pass


@dataclass
class Segment:
    name: str
    tokens: int
    referents: Set[str] = field(default_factory=set)
    summary_depth: int = 0
    priority: float = 0.0


@dataclass
class PolicyState:
    eviction_threshold: float
    allocations: Dict[str, int] = field(default_factory=dict)
    priorities: Dict[str, float] = field(default_factory=dict)


def apply_self_edit(
    state: PolicyState,
    segments: Dict[str, Segment],
    budget: int,
    operator_threshold: float,
    threshold_tolerance: float = 0.05,
    max_orphan_ratio: float = 0.10,
    max_summary_depth: int = 1,
) -> PolicyState:
    """Validate a proposed self-edit against structural invariants before admitting it."""
    total = sum(s.tokens for s in segments.values())
    if total > budget:
        raise ContextInvariantError(
            f"proposed edit exceeds budget: {total} > {budget}"
        )

    # Signal 1: referent orphaning ratio.
    all_referents: Set[str] = set()
    for s in segments.values():
        all_referents |= s.referents
    orphans = sum(1 for s in segments.values() if not s.referents)
    orphan_ratio = orphans / max(len(segments), 1)
    if orphan_ratio > max_orphan_ratio:
        raise ContextInvariantError(
            f"referent orphaning ratio {orphan_ratio:.2f} exceeds {max_orphan_ratio}; revert, do not repair"
        )

    # Signal 2: summary depth compounding.
    for s in segments.values():
        if s.summary_depth > max_summary_depth:
            raise ContextInvariantError(
                f"segment {s.name!r} summary depth {s.summary_depth} exceeds {max_summary_depth}"
            )

    # Signal 3: priority inversion at equal cost with no task-objective delta.
    for name, seg in segments.items():
        prev = state.priorities.get(name)
        if prev is not None and abs(seg.priority - prev) > 0.0 and seg.tokens == state.allocations.get(name, seg.tokens):
            raise ContextInvariantError(
                f"priority inversion on {name!r} at unchanged cost; edit is a fixpoint of itself"
            )

    # Signal 4: cumulative eviction-threshold drift.
    drift = abs(state.eviction_threshold - operator_threshold)
    if drift > threshold_tolerance:
        raise ContextInvariantError(
            f"eviction threshold drifted {drift:.3f} from operator value {operator_threshold}; revert and raise"
        )

    # Admit the edit only after all structural checks pass.
    new_state = PolicyState(
        eviction_threshold=state.eviction_threshold,
        allocations={n: s.tokens for n, s in segments.items()},
        priorities={n: s.priority for n, s in segments.items()},
    )
    return new_state
