# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-model-authored-context-pruning-directive-because-the-pruning-policy-has-become-self-referentially.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-model-authored-context-pruning-directive-because-the-pruning-policy-has-become-self-referentially.warrant.json
# Markdown SHA-256:   be4abb86e007c6b3e268046264922b464fb4b9c12e236e1e940a75b3e091f7ea
# Code AST SHA-256:   aa96ffde8c78741c552d35928b14bf59aa67b726997f9653e08bc2099777a9a3
# Verified Classes:   PolicySelfReferenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicySelfReferenceError(RuntimeError):
    """Raised when a model-authored prune directive targets an anchor or
    justification segment that the model is not authorized to remove."""
    pass


ANCHOR_IDS = {"task_spec", "acceptance_criteria", "policy_amendment_log"}


def validate_prune_directive(directive, live_anchors):
    # directive: {"targets": [seg_id, ...], "justification": str}
    targets = set(directive.get("targets", []))
    if not targets:
        raise PolicySelfReferenceError("empty prune directive; refusing no-op amendment")

    hit = targets & ANCHOR_IDS
    if hit:
        raise PolicySelfReferenceError(
            f"directive targets protected anchor(s) {sorted(hit)}; "
            f"model may not prune the grounds of its own policy"
        )

    # A directive that removes justification segments is only valid if the
    # effects they justified are final and the anchors remain sufficient.
    if directive.get("prunes_justifications"):
        remaining = live_anchors - targets
        if len(remaining) < len(ANCHOR_IDS):
            raise PolicySelfReferenceError(
                "pruning justification would leave insufficient anchor set "
                f"({sorted(remaining)}); escalation required"
            )

    return True


def apply_self_amendment(directive, live_anchors, ledger):
    validate_prune_directive(directive, live_anchors)
    ledger.append({"event": "prune", "targets": directive["targets"],
                   "justification": directive["justification"]})
    return live_anchors - set(directive["targets"])
