# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-fidelity-at-the-context-window-safe-boundary-even-when-token-count-is-under-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-fidelity-at-the-context-window-safe-boundary-even-when-token-count-is-under-budget.warrant.json
# Markdown SHA-256:   2a7f566bc94b373704c0fb15c6dd5a616a7c80f1c23362b5b480b50cd598ec54
# Code AST SHA-256:   0f48d788b53cf20741651481217e02add2c2c4dbf9eae3b3539a1a35ac6a9ad4
# Verified Classes:   LayoutViolation, Salience, Segment, ContextLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class LayoutViolation(RuntimeError):
    """Raised when a layout operation would displace a pinned-salient constraint."""
    pass


class Salience(Enum):
    PINNED = "pinned"          # full retention, stable high-attention position
    DEMOTABLE = "demotable"    # may be summarized/relocated
    CLOSED = "closed"          # scope provably ended; may be dropped


@dataclass
class Segment:
    seg_id: str
    tokens: int
    salience: Salience
    irreversible_scope: bool = False
    text: str = ""


@dataclass
class ContextLedger:
    budget: int
    segments: dict[str, Segment] = field(default_factory=dict)

    def total_tokens(self) -> int:
        return sum(s.tokens for s in self.segments.values())

    def register(self, seg: Segment) -> None:
        if seg.irreversible_scope and seg.salience is not Salience.PINNED:
            raise LayoutViolation(
                f"segment {seg.seg_id} bounds irreversible actions but is "
                f"{seg.salience.value}; must be PINNED at registration"
            )
        self.segments[seg.seg_id] = seg

    def demote(self, seg_id: str, reason: str) -> None:
        seg = self.segments[seg_id]
        if seg.salience is Salience.PINNED and seg.irreversible_scope:
            raise LayoutViolation(
                f"refusing to demote pinned-salient segment {seg_id} "
                f"(reason={reason!r}); budget headroom "
                f"{self.budget - self.total_tokens()} tokens does NOT "
                f"authorize displacement of an irreversible-scope constraint"
            )
        seg.salience = Salience.DEMOTABLE

    def assert_action_allowed(self, action: str, target: str) -> None:
        # Any retained constraint (pinned OR demoted-but-not-closed) whose
        # text names the target must block the action, regardless of budget.
        for seg in self.segments.values():
            if seg.salience is Salience.CLOSED:
                continue
            if target in seg.text and "forbid" in seg.text.lower():
                raise LayoutViolation(
                    f"action {action!r} on {target!r} blocked by constraint "
                    f"{seg.seg_id} (salience={seg.salience.value}); "
                    f"token budget was {self.budget}, used {self.total_tokens()}"
                )


def plan_layout(ledger: ContextLedger, demotions: list[str]) -> None:
    for seg_id in demotions:
        ledger.demote(seg_id, reason="age_threshold_heuristic")


def execute(ledger: ContextLedger, action: str, target: str) -> None:
    ledger.assert_action_allowed(action, target)


if __name__ == "__main__":
    ledger = ContextLedger(budget=96_000)
    ledger.register(Segment("sys", 800, Salience.PINNED))
    ledger.register(Segment(
        "c_turn4", 41, Salience.PINNED, irreversible_scope=True,
        text="forbid overwrite of config/*.lock; append only",
    ))
    ledger.register(Segment("tool_results", 70_000, Salience.DEMOTABLE))

    # Age heuristic tries to fold the constraint into a digest:
    plan_layout(ledger, ["c_turn4"])   # raises LayoutViolation here
    execute(ledger, "overwrite_file", "config/db.lock")
