# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-authored-context-pruning-when-the-rewrite-policy-is-itself-part-of-the-context-it-prunes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-authored-context-pruning-when-the-rewrite-policy-is-itself-part-of-the-context-it-prunes.warrant.json
# Markdown SHA-256:   144c5656b107f38b39e9a54bc6b4e31155b09a9b681392611aad0c83d8b38be9
# Code AST SHA-256:   315b0294dc85362dc5e8c7f73006c9fffc94027fb4e7a283f6eea8e97c22e4d7
# Verified Classes:   PolicyDriftError, PolicySpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PolicyDriftError(RuntimeError):
    """Raised when a self-edit mutates the pruning policy or its exclusion set."""
    pass


@dataclass(frozen=True)
class PolicySpan:
    offset: int
    text: str

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()


def apply_self_edit(context: str, policy: PolicySpan, rewrite) -> str:
    """
    Apply a model-authored pruning rewrite, but only if the policy span
    survives byte-identical. The exclusion set is evaluated against the
    PRE-edit policy, never the post-edit context.
    """
    pre_digest = policy.digest()
    edited = rewrite(context)

    # Recover the policy span from the edited context by its recorded offset,
    # NOT by a tag the rewrite could have moved or paraphrased.
    end = policy.offset + len(policy.text)
    if end > len(edited):
        raise PolicyDriftError(
            f"policy span truncated: expected {len(policy.text)} chars at "
            f"offset {policy.offset}, context now {len(edited)} chars"
        )
    post_span = edited[policy.offset:end]
    post_digest = hashlib.sha256(post_span.encode("utf-8")).hexdigest()

    if post_digest != pre_digest:
        raise PolicyDriftError(
            "self-edit mutated the policy span; refusing pass. "
            f"pre={pre_digest[:12]} post={post_digest[:12]}"
        )

    # Exclusion set must be honored against the pre-edit policy's clauses.
    if "#keep" in policy.text and "#keep" not in edited:
        raise PolicyDriftError("exclusion-tagged span evicted despite #keep clause")

    return edited


def compact(context: str, policy: PolicySpan, rewrite) -> str:
    try:
        return apply_self_edit(context, policy, rewrite)
    except PolicyDriftError:
        # Halt compaction; recover budget elsewhere or escalate out-of-band.
        raise
