# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-a-rewrite-budget-when-salience-weighted-pruning-re-admits-the-same-spans-across-successive-self-edits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-a-rewrite-budget-when-salience-weighted-pruning-re-admits-the-same-spans-across-successive-self-edits.warrant.json
# Markdown SHA-256:   de262131fb267d77c73526fc228ff97fe76d8866e13972c42c88c32ce48e7387
# Code AST SHA-256:   71c0bfc50d7ccbae5d12f617347591b05f3428c5c679b547d3ed2de5f082034a
# Verified Classes:   RewriteBudgetExceeded, ContextSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RewriteBudgetExceeded(RuntimeError):
    """Raised when a span is selected for rewrite beyond its identity-keyed budget."""
    pass


class ContextSpan:
    def __init__(self, span_id: str, content: str, tokens: int, salience: float, is_primary_source: bool):
        self.span_id = span_id
        self.content = content
        self.tokens = tokens
        self.salience = salience            # content-derived at ingestion
        self.is_primary_source = is_primary_source
        self.rewrite_count = 0
        self.frozen = False


REWRITE_BUDGET = {"tool_output": 2, "reasoning": 3}


def select_for_rewrite(span: ContextSpan, kind: str, fresh_source_conflict: bool) -> bool:
    """Decide whether a span may be rewritten again this compaction cycle."""
    if span.is_primary_source and fresh_source_conflict:
        # primary source wins on conflict; never rewrite it down
        return False
    if span.frozen:
        return False
    budget = REWRITE_BUDGET[kind]
    if span.rewrite_count >= budget:
        # budget exhausted: freeze, do not rewrite, do not raise here --
        # eviction path handles it. Raising here is a caller bug.
        raise RewriteBudgetExceeded(
            f"span {span.span_id} at rewrite_count={span.rewrite_count} "
            f">= budget={budget} for kind={kind}; must evict or freeze, not rewrite"
        )
    return True


def apply_rewrite(span: ContextSpan, kind: str, new_content: str, new_tokens: int,
                  new_salience: float, fresh_source_conflict: bool) -> None:
    if not select_for_rewrite(span, kind, fresh_source_conflict):
        span.frozen = True
        return
    if new_salience > span.salience:
        # drift signal: cap salience at ingestion value, never let it rise on rewrite
        span.salience = span.salience
    else:
        span.salience = new_salience
    span.content = new_content
    span.tokens = new_tokens
    span.rewrite_count += 1
    if span.rewrite_count >= REWRITE_BUDGET[kind]:
        span.frozen = True


def compact(spans: list[ContextSpan], token_target: int) -> list[ContextSpan]:
    kept = sorted(spans, key=lambda s: s.salience, reverse=True)
    total = 0
    out = []
    for s in kept:
        if total + s.tokens <= token_target:
            out.append(s)
            total += s.tokens
    return out
