# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-silently-widened-its-own-guardrail-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-silently-widened-its-own-guardrail-envelope.warrant.json
# Markdown SHA-256:   952daa12c3807bd94a0bbbd718c182dccd0048cddedd9c5e11a758fec3242bb8
# Code AST SHA-256:   1c61cc3ea654848ad55b95b78c0e29deecc57bd63aaa15b594e357bc229039cf
# Verified Classes:   GuardrailEnvelopeWidened, ContextSnapshot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class GuardrailEnvelopeWidened(RuntimeError):
    """Raised when a self-edit passes per-edit checks but drifts the protected region."""
    pass


@dataclass
class ContextSnapshot:
    text: str
    protected_headings: frozenset
    modality_counts: dict


def _hash_protected(text: str, headings: frozenset) -> str:
    # Content-addressed: address the protected region by what it says, not where it lives.
    lines = [ln for ln in text.splitlines() if any(h in ln for h in headings)]
    return hashlib.sha256("\n".join(lines).encode()).hexdigest()


def _modality_counts(text: str) -> dict:
    lowered = text.lower()
    return {
        "must": lowered.count("must"),
        "shall": lowered.count("shall"),
        "may_not": lowered.count("may not"),
    }


def apply_self_edit(baseline: ContextSnapshot, candidate_text: str,
                    per_edit_diff_tokens: int, diff_cap: int = 400) -> ContextSnapshot:
    # Per-edit check: bounded diff. Necessary, not sufficient.
    if per_edit_diff_tokens > diff_cap:
        raise GuardrailEnvelopeWidened(
            f"diff {per_edit_diff_tokens} exceeds cap {diff_cap}"
        )

    # Ratchet check 1: protected region must be byte-identical to the session baseline,
    # addressed by content hash -- never regenerated from the post-edit state.
    if _hash_protected(candidate_text, baseline.protected_headings) != \
       _hash_protected(baseline.text, baseline.protected_headings):
        raise GuardrailEnvelopeWidened(
            "protected region drifted from session-anchored baseline "
            "(relocation or refactor under a passing key-presence check)"
        )

    # Ratchet check 2: deontic modality must be monotonic non-decreasing.
    cand = _modality_counts(candidate_text)
    for key, before in baseline.modality_counts.items():
        if cand[key] < before:
            raise GuardrailEnvelopeWidened(
                f"modality erosion in '{key}': {before} -> {cand[key]} "
                "(prohibition concept present, deontic strength reduced)"
            )

    return ContextSnapshot(
        text=candidate_text,
        protected_headings=baseline.protected_headings,
        modality_counts=cand,
    )
