# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-rewriting-their-own-reconciliation-preconditions-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-policies-from-silently-rewriting-their-own-reconciliation-preconditions-mid-flight.warrant.json
# Markdown SHA-256:   82a937391cfb3c5b0b65694f677aecb4257508d476ba77294d5dc9561e44b397
# Code AST SHA-256:   e4f2720fbf40c7cedd61e21f2235bb7661e60316d64221d976b7cd61a84185fa
# Verified Classes:   ReconciliationInvariantError, Directive, FrozenMetaPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Modality = Literal["hard", "soft"]
HARD_TOKENS = {"only", "never", "must", "mark", "always"}


class ReconciliationInvariantError(RuntimeError):
    """Raised when a self-edit would mutate the reconciliation meta-policy
    or invert a guard's operative rank mid-epoch."""
    pass


@dataclass(frozen=True)
class Directive:
    id: str
    text: str
    modality: Modality
    priority: int
    is_guard: bool = False


@dataclass
class FrozenMetaPolicy:
    # Frozen for the task epoch. Editing this is the out-of-bounds boundary.
    tie_break: str = "recency"
    guard_floor: int = 100

    def assert_untouched(self, proposed_tie_break: str) -> None:
        if proposed_tie_break != self.tie_break:
            raise ReconciliationInvariantError(
                f"self-edit attempted to mutate tie-break "
                f"{self.tie_break!r} -> {proposed_tie_break!r}; "
                f"meta-policy is immutable within an epoch"
            )


def modality_weakened(old: Directive, new: Directive) -> bool:
    if old.modality == "hard" and new.modality == "soft":
        return True
    old_hard = any(t in old.text.lower().split() for t in HARD_TOKENS)
    new_hard = any(t in new.text.lower().split() for t in HARD_TOKENS)
    return old_hard and not new_hard


def commit_self_edit(
    current: dict[str, Directive],
    proposed: Directive,
    meta: FrozenMetaPolicy,
    proposed_tie_break: str,
) -> dict[str, Directive]:
    # 1. The edit may not touch the referee.
    meta.assert_untouched(proposed_tie_break)

    old = current.get(proposed.id)

    # 2. Guard-reachable directive may not have its modality softened.
    if old is not None and old.is_guard and modality_weakened(old, proposed):
        raise ReconciliationInvariantError(
            f"edit to guard {proposed.id!r} weakens hard modality; "
            f"refusing in-place commit, escalate to handoff"
        )

    # 3. Projected ordering must not place an edited directive above a guard.
    guards = [d for d in current.values() if d.is_guard and d.id != proposed.id]
    if proposed.priority > meta.guard_floor and guards:
        raise ReconciliationInvariantError(
            f"edit to {proposed.id!r} assigns priority {proposed.priority} "
            f"above guard floor {meta.guard_floor}; rank inversion blocked"
        )

    updated = dict(current)
    updated[proposed.id] = proposed
    return updated
