# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-self-rewrite-of-its-working-memory-policy-under-budget-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-self-rewrite-of-its-working-memory-policy-under-budget-pressure.warrant.json
# Markdown SHA-256:   01ef6d23128ceb57a15ce5dbca7681632dffc894d8ce940571299403a59f0fec
# Code AST SHA-256:   92e0d52295c55c7eca3ea7c19bc67f1061850ce76e97fd7bfe70359a29d17fb9
# Verified Classes:   EndogenousMeterRewriteError, WorkingMemoryPolicy, ContextMeter, Agent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class EndogenousMeterRewriteError(RuntimeError):
    """Raised when a policy rewrite would alter the meter that justifies it."""
    pass


@dataclass
class WorkingMemoryPolicy:
    summarize_threshold: float
    eviction_order: str            # "oldest_first" | "recent_plus_pinned"
    counts_toward_budget: Callable[[str], bool]
    # NOTE: estimated_tokens is the endogenous meter. It lives here on purpose
    # so that the guard below can detect when a rewrite would touch it.
    estimated_tokens: int = 0


@dataclass
class ContextMeter:
    """Exogenous, read-only meter injected by the runtime."""
    actual_serialized_tokens: int
    budget: int

    @property
    def utilization(self) -> float:
        return self.actual_serialized_tokens / self.budget


@dataclass
class Agent:
    policy: WorkingMemoryPolicy
    meter: ContextMeter
    pinned: list = field(default_factory=list)

    def rewrite_policy(self, new_policy: WorkingMemoryPolicy) -> None:
        # The rewrite is admissible only if the meter that justifies it is
        # not itself modified by the rewrite. estimated_tokens is the
        # endogenous meter; if the new policy changes its role or the
        # threshold it is compared against, the justification is circular.
        touches_endogenous_meter = (
            new_policy.estimated_tokens != self.policy.estimated_tokens
            or new_policy.counts_toward_budget is not self.policy.counts_toward_budget
        )
        threshold_moved = (
            new_policy.summarize_threshold != self.policy.summarize_threshold
        )
        order_moved = new_policy.eviction_order != self.policy.eviction_order

        if (threshold_moved or order_moved) and touches_endogenous_meter:
            raise EndogenousMeterRewriteError(
                "policy rewrite is justified by a meter the rewrite would "
                "alter; seek exogenous confirmation before proceeding"
            )

        # Even with an untouched meter, post-rewrite exogenous measurement
        # must confirm margin. If it does not, refuse rather than trust the
        # endogenous estimate.
        if self.meter.utilization > new_policy.summarize_threshold:
            raise EndogenousMeterRewriteError(
                f"post-rewrite exogenous utilization "
                f"{self.meter.utilization:.2f} exceeds new threshold "
                f"{new_policy.summarize_threshold:.2f}; compact contents "
                f"or request scratch buffer instead"
            )

        self.policy = new_policy
