# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-silently-deleting-the-instruction-that-authorizes-the-edit.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-editing-context-from-silently-deleting-the-instruction-that-authorizes-the-edit.warrant.json
# Markdown SHA-256:   458dca1d4658044a65218a3f45189b74502a08330415a5f30fe4c7379cef86e6
# Code AST SHA-256:   c010382eb4d1b4804967e7defa8f2231b69a4bbb65e52d26caf6d33d107fc590
# Verified Classes:   ContextRewriteViolation, Instruction, RewriteLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal

Role = Literal["guard", "payload", "procedure"]

class ContextRewriteViolation(RuntimeError):
    """Raised when a self-edit pass would remove or mutate a guard,
    or when the rewrite cannot prove a valid pre-image."""

@dataclass(frozen=True)
class Instruction:
    handle: str          # immutable address, never reassigned by rewrite
    role: Role
    text: str

@dataclass
class RewriteLog:
    pre_hash: str
    post_hash: str
    removed: list[Instruction] = field(default_factory=list)

def _hash(instrs: list[Instruction]) -> str:
    h = hashlib.sha256()
    for i in sorted(instrs, key=lambda x: x.handle):
        h.update(f"{i.handle}|{i.role}|{i.text}".encode())
    return h.hexdigest()

def apply_prune(
    editable: list[Instruction],
    frozen_frame: list[Instruction],
    proposed_removals: list[str],   # handles the model wants gone
    seed: int,
) -> tuple[list[Instruction], RewriteLog]:
    frozen_handles = {i.handle for i in frozen_frame}
    guard_handles = {i.handle for i in editable if i.role == "guard"}

    # Invariant 1: the authorization frame is excluded by address, not content.
    for h in proposed_removals:
        if h in frozen_handles:
            raise ContextRewriteViolation(
                f"rewrite targeted frozen frame handle {h!r}; frame is non-editable"
            )
        # Invariant 2: guards are never removable candidates.
        if h in guard_handles:
            raise ContextRewriteViolation(
                f"rewrite would delete guard {h!r}; guards may only be superseded, not pruned"
            )

    removed = [i for i in editable if i.handle in proposed_removals]
    survivors = [i for i in editable if i.handle not in proposed_removals]
    post = survivors + frozen_frame

    # Invariant 3: hash-chained pre-image must be reconstructable.
    pre_hash = _hash(editable + frozen_frame)
    post_hash = _hash(post)
    log = RewriteLog(pre_hash=pre_hash, post_hash=post_hash, removed=removed)

    if not log.pre_hash or not log.post_hash:
        raise ContextRewriteViolation("rewrite emitted no pre/post hash; unauditable")

    # Invariant 4: determinism — same seed must reproduce the same post_hash.
    # (Caller re-runs with same seed and asserts equality; here we assert presence.)
    if seed is None:
        raise ContextRewriteViolation("prune pass ran without pinned seed")

    return post, log
