# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-to-prevent-salience-score-collapse-during-long-horizon-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-to-prevent-salience-score-collapse-during-long-horizon-runs.warrant.json
# Markdown SHA-256:   effceb37830a5869fc7b75c0af8fab209bd7b7aa642849a4fe616e46b62ca7ef
# Code AST SHA-256:   565551a42d37f933d75ee06b2631cf88ccabd9c7d68bff01afe5123fb19e85fc
# Verified Classes:   RewriteRefused, SpanClass, Span, DereferenceLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RewriteRefused(RuntimeError):
    """Raised when a model-issued rewrite violates the reference-closure or recoverability invariant."""


class SpanClass(Enum):
    PROSE = "prose"                 # model-authored, no tool literals
    TOOL_RESULT = "tool_result"     # verbatim tool return
    USER_CONSTRAINT = "user_constraint"  # negative/positive user directive
    LEDGER = "ledger"               # dereference ledger itself


@dataclass
class Span:
    index: int
    klass: SpanClass
    text: str
    literals: frozenset[str] = frozenset()   # verbatim values later steps may dereference
    raw_pointer: Optional[str] = None        # out-of-window store key for recoverable surrogates


@dataclass
class DereferenceLedger:
    # literal classes any registered tool signature can require on a *future* call
    required_literals: set[str] = field(default_factory=set)

    def closes(self, literals: frozenset[str]) -> bool:
        return literals <= self.required_literals


def apply_rewrite(
    span: Span,
    replacement: str,
    salience: float,
    ledger: DereferenceLedger,
    *,
    salience_threshold: float = 0.25,
) -> Span:
    """
    Runtime gate for a model-issued rewrite. Salience is a tiebreaker among
    already-eligible spans; it is NEVER the eligibility predicate.
    """
    # Invariant 1: eligibility is decided by span class, not by salience.
    if span.klass in (SpanClass.LEDGER, SpanClass.USER_CONSTRAINT):
        raise RewriteRefused(
            f"span {span.index} is {span.klass.value}; user constraints and the "
            f"ledger are never rewritable regardless of salience={salience:.2f}"
        )

    if span.klass == SpanClass.TOOL_RESULT:
        # Invariant 2: tool results may only be rewritten if their literals are
        # provably not future-dereferenced AND the raw span is recoverable.
        if not ledger.closes(span.literals):
            missing = span.literals - ledger.required_literals
            raise RewriteRefused(
                f"span {span.index} contains future-dereferenced literals "
                f"{sorted(missing)}; reference closure fails"
            )
        if span.raw_pointer is None:
            raise RewriteRefused(
                f"span {span.index} has no recoverable pointer; rewriting would "
                f"delete the referent rather than compress it"
            )

    # Invariant 3: salience may only *veto*, never *authorize*. A low-salience
    # eligible span is still rewritten only if the caller already chose to.
    if salience < salience_threshold and span.klass == SpanClass.PROSE:
        # permitted, but recorded as a salience-driven rewrite for audit
        pass

    return Span(
        index=span.index,
        klass=span.klass,
        text=replacement,
        literals=frozenset(),          # surrogate carries no verbatim literals
        raw_pointer=span.raw_pointer,  # pointer survives the rewrite
    )


def dereference(span: Span, literal: str) -> str:
    """Later step needs a verbatim value; recover it or fail loudly."""
    if literal in span.text:
        return span.text
    if span.raw_pointer is not None:
        return f"<recovered from {span.raw_pointer}>"
    raise RewriteRefused(
        f"literal {literal!r} was pruned from span {span.index} with no recoverable "
        f"pointer; the agent cannot detect this loss in-context"
    )
