# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-when-the-pruner-s-own-rationale-is-itself-pruneable.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-model-driven-context-rewriting-when-the-pruner-s-own-rationale-is-itself-pruneable.warrant.json
# Markdown SHA-256:   311fe0dcab421d0817ea1e9391640496f141317195a7d550152a94fae7998b00
# Code AST SHA-256:   bc6db71e603dd34902f67457c51a7cb0920a49ccb5cc86fbe57f7cffc720adad
# Verified Classes:   PolicyEvictionViolation, RetentionClause, ContextState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class PolicyEvictionViolation(RuntimeError):
    """Raised when a self-edit pass attempts to drop a committed retention clause."""


@dataclass
class RetentionClause:
    key: str
    reason: str
    committed_at_step: int
    superseded: bool = False


@dataclass
class ContextState:
    content: dict[str, Any]
    policy: dict[str, RetentionClause] = field(default_factory=dict)
    revision_log: list[dict[str, Any]] = field(default_factory=list)


def self_edit(
    state: ContextState,
    step: int,
    drop_content_keys: list[str],
    propose_policy_drops: list[str],
) -> ContextState:
    # Content is freely prunable; policy clauses are not, within the same pass.
    new_content = {k: v for k, v in state.content.items() if k not in drop_content_keys}

    for key in propose_policy_drops:
        clause = state.policy.get(key)
        if clause is None:
            continue
        if not clause.superseded:
            raise PolicyEvictionViolation(
                f"self-edit at step {step} tried to evict committed clause "
                f"{key!r} (committed at step {clause.committed_at_step}, "
                f"reason={clause.reason!r}) without a supersession revision"
            )

    new_policy = dict(state.policy)
    new_log = list(state.revision_log)
    new_log.append(
        {"step": step, "dropped_content": drop_content_keys, "policy_drops_attempted": propose_policy_drops}
    )
    return ContextState(content=new_content, policy=new_policy, revision_log=new_log)


def supersede_clause(state: ContextState, key: str, step: int, reason: str) -> ContextState:
    if key not in state.policy:
        raise PolicyEvictionViolation(f"cannot supersede unknown clause {key!r}")
    new_policy = dict(state.policy)
    old = new_policy[key]
    new_policy[key] = RetentionClause(
        key=old.key, reason=reason, committed_at_step=step, superseded=True
    )
    new_log = list(state.revision_log)
    new_log.append({"step": step, "superseded": key, "reason": reason})
    return ContextState(content=state.content, policy=new_policy, revision_log=new_log)
