# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-precondition-of-their-own-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-pruning-agents-from-deleting-the-precondition-of-their-own-rewrite.warrant.json
# Markdown SHA-256:   8a01dea0297fd39bbf4927cbeeadb04a8d7cb7bc62aaa2850d849f493712ca68
# Code AST SHA-256:   672ec3fbdcf5780320a761b87e1f920417e5aa4e4507c5c4b02a8b897aec500f
# Verified Classes:   WarrantViolation, Segment, Warrant, SelfPruneGuard
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class WarrantViolation(RuntimeError):
    """Raised when a self-prune deletes a segment whose justification cannot
    survive the deletion, or when a downstream action contradicts a warrant."""
    pass


@dataclass
class Segment:
    seg_id: str
    content: str
    kind: str  # "task" | "fact" | "negative_constraint" | "tool_binding"
    pinned: bool = False

    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()[:16]


@dataclass
class Warrant:
    seg_id: str
    content_hash: str
    reason: str
    pre_prune_snapshot: dict  # seg_id -> content at decision time


class SelfPruneGuard:
    """Enforces the Warrant-Preservation Invariant: a deletion is committed only
    if its warrant is structured, stored outside the mutable window, and
    consistent with the pre-prune snapshot."""

    PROTECTED_KINDS = {"negative_constraint", "tool_binding"}

    def __init__(self, window: list[Segment]):
        self.window = {s.seg_id: s for s in window}
        self.ledger: list[Warrant] = []

    def propose_prune(self, drop_ids: list[str], reasons: dict[str, str]) -> list[Warrant]:
        snapshot = {sid: s.content for sid, s in self.window.items()}
        warrants: list[Warrant] = []
        for sid in drop_ids:
            seg = self.window.get(sid)
            if seg is None:
                raise WarrantViolation(f"prune proposed for absent segment {sid}")
            if seg.pinned or seg.kind in self.PROTECTED_KINDS:
                raise WarrantViolation(
                    f"segment {sid} ({seg.kind}) is protected; cannot be pruned by model policy"
                )
            reason = reasons.get(sid)
            if not reason or len(reason.strip()) < 8:
                raise WarrantViolation(
                    f"segment {sid} lacks a structured warrant; free-text or empty reasons are not replayable"
                )
            warrants.append(Warrant(sid, seg.content_hash(), reason, snapshot))
        return warrants

    def commit(self, warrants: list[Warrant]) -> None:
        for w in warrants:
            seg = self.window[w.seg_id]
            if seg.content_hash() != w.content_hash:
                raise WarrantViolation(
                    f"warrant hash mismatch for {w.seg_id}: window changed between decision and commit"
                )
            # Warrant is stored outside the mutable window before the segment leaves it.
            self.ledger.append(w)
            del self.window[w.seg_id]

    def assert_action_allowed(self, subject: str, action: str) -> None:
        """Replay warrants against a proposed downstream action. A deletion
        justified as 'not the target' is void if the action now targets it."""
        for w in self.ledger:
            if subject in w.pre_prune_snapshot.get(w.seg_id, ""):
                raise WarrantViolation(
                    f"action {action!r} on {subject!r} touches a segment ({w.seg_id}) "
                    f"deleted under warrant {w.reason!r}; warrant is void for this subject"
                )
        for seg in self.window.values():
            if seg.kind == "negative_constraint" and subject in seg.content and action == "write":
                raise WarrantViolation(
                    f"action {action!r} on {subject!r} blocked by pinned constraint {seg.seg_id}"
                )


# --- failure trace: the unsafe path ---
def unsafe_self_prune(window: list[Segment], drop_ids: list[str]) -> list[Segment]:
    """No guard: model rewrites its own window and its own justification."""
    kept = [s for s in window if s.seg_id not in drop_ids]
    return kept  # the reason 'db-prod-3 is deprecated' is now unrecoverable


# --- guarded path ---
def guarded_prune_and_act() -> None:
    window = [
        Segment("t1", "migrate schema on prod DB", "task"),
        Segment("f1", "db-prod-7 is the target host", "fact"),
        Segment("c1", "do not touch db-prod-3 (deprecated, replica lag)", "negative_constraint"),
    ]
    guard = SelfPruneGuard(window)

    # Model wants to reclaim budget by dropping the constraint as low-salience.
    try:
        guard.propose_prune(drop_ids=["c1"], reasons={"c1": "not the target host"})
    except WarrantViolation as e:
        # Correct outcome: protected class refuses the prune.
        assert "protected" in str(e)

    # Model drops a benign fact with a structured warrant, then later acts on its subject.
    warrants = guard.propose_prune(drop_ids=["f1"], reasons={"f1": "target host already recorded in task t1"})
    guard.commit(warrants)
    try:
        guard.assert_action_allowed(subject="db-prod-7", action="write")
    except WarrantViolation:
        raise WarrantViolation("unexpected: warrant for f1 should not block the recorded target")
