# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-rewrite-its-own-scratchpad-the-self-editing-context-policy-and-the-read-after-write-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-rewrite-its-own-scratchpad-the-self-editing-context-policy-and-the-read-after-write-divergence-boundary.warrant.json
# Markdown SHA-256:   5a9c1fbe419d287fa3741d1fc35389696f872dba361a1b0afcce132bd00bfeb4
# Code AST SHA-256:   e678b14feb9cca6321910ecc87339de70d4d1d2ba6b3bea9347f3080efa95a18
# Verified Classes:   RewriteRefused, PropositionKind, Proposition, Region, RewritePlan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class RewriteRefused(RuntimeError):
    """Raised when a self-editing context policy attempts an unsound rewrite."""


class PropositionKind(Enum):
    FACT = "fact"
    NEGATION = "negation"
    BOUND = "bound"
    TIE_BREAKER = "tie_breaker"
    EXCEPTION = "exception"


# Kinds whose truth value is destroyed by paraphrase; must survive verbatim.
FRAGILE = {PropositionKind.NEGATION, PropositionKind.BOUND,
           PropositionKind.TIE_BREAKER, PropositionKind.EXCEPTION}


@dataclass(frozen=True)
class Proposition:
    pid: str
    text: str
    kind: PropositionKind
    discharged: bool = False

    def __post_init__(self) -> None:
        if not self.pid:
            raise RewriteRefused("proposition without stable id cannot be tracked across rewrites")


@dataclass
class Region:
    name: str
    propositions: list[Proposition] = field(default_factory=list)

    def undischarged(self) -> list[Proposition]:
        return [p for p in self.propositions if not p.discharged]

    def content_hash(self) -> str:
        blob = "\n".join(f"{p.pid}:{p.kind.value}:{p.text}" for p in self.propositions)
        return hashlib.sha256(blob.encode()).hexdigest()


@dataclass
class RewritePlan:
    region: Region
    preserved_pids: set[str]
    trigger_occupancy: float
    tool_call_in_flight: bool


def authorize_rewrite(plan: RewritePlan, occupancy_threshold: float = 0.78) -> str:
    """
    Enforce the Scratchpad Rewrite Safety invariant. Returns the content hash
    of the pre-rewrite region on success; raises RewriteRefused otherwise.
    Occupancy is a trigger, never an authorization.
    """
    if plan.tool_call_in_flight:
        raise RewriteRefused(
            f"region {plan.region.name!r}: rewrite during in-flight tool call "
            "leaves call arguments undischarged"
        )

    for p in plan.region.undischarged():
        if p.kind in FRAGILE and p.pid not in plan.preserved_pids:
            raise RewriteRefused(
                f"region {plan.region.name!r}: undischarged {p.kind.value} "
                f"proposition {p.pid!r} would be paraphrased or dropped; "
                "externalize and retain handle instead"
            )
        if p.pid not in plan.preserved_pids:
            raise RewriteRefused(
                f"region {plan.region.name!r}: undischarged proposition {p.pid!r} "
                "not preserved verbatim"
            )

    if plan.trigger_occupancy >= occupancy_threshold and not plan.preserved_pids:
        raise RewriteRefused(
            f"region {plan.region.name!r}: occupancy {plan.trigger_occupancy:.0%} "
            "triggered rewrite with no preserved propositions; occupancy is not discharge"
        )

    return plan.region.content_hash()


def externalize(region: Region) -> str:
    """Persist the region and return a stable handle to keep in context."""
    digest = region.content_hash()
    # durable store write omitted; handle is content-addressed
    return f"mem://{region.name}/{digest[:16]}"


# --- reproduced failure trace from the operational record ---
scratchpad = Region("planning", [
    Proposition("C7", "output rows sorted by (ts, id) ascending; ties by id; DO NOT sort by ts alone",
                PropositionKind.TIE_BREAKER, discharged=False),
    Proposition("OBS-52", "display table used descending ts order", PropositionKind.FACT, discharged=True),
])

try:
    authorize_rewrite(RewritePlan(
        region=scratchpad,
        preserved_pids=set(),           # summarizer dropped the tie-breaker
        trigger_occupancy=0.79,         # crossed the 78% threshold
        tool_call_in_flight=False,
    ))
except RewriteRefused as exc:
    handle = externalize(scratchpad)
    print(f"rewrite blocked: {exc}")
    print(f"externalized to {handle}; handle retained in context")
