# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-the-self-referential-pruning-loop-when-a-model-edits-its-own-working-memory-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-the-self-referential-pruning-loop-when-a-model-edits-its-own-working-memory-policy.warrant.json
# Markdown SHA-256:   1f720ca464339ff09497fa1d7ce51aa71d62b44870cb3e36628599e037c14497
# Code AST SHA-256:   72c47646e4aad44d7f07d60b113c20b8d84515deb46b143d952743e53ea53d85
# Verified Classes:   SelfEditInvariantViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SelfEditInvariantViolation(RuntimeError):
    """Raised when a model-driven context policy edit would mutate a non-editable field
    or when the policy-edit loop fails to converge."""
    pass


NON_EDITABLE_FIELDS = frozenset({
    "prune_threshold",
    "termination_predicate",
    "protect",            # removal forbidden; additions allowed
    "acceptance_criteria",
    "revision_provenance",
})


def apply_policy_edit(current_policy: dict, proposed_edit: dict,
                      verifier_approved: bool,
                      policy_hash_history: list[str],
                      churn_limit: float = 0.5) -> dict:
    # 1. Reject edits that touch non-editable fields unless a verifier approved.
    touched = set(proposed_edit.keys())
    forbidden = touched & NON_EDITABLE_FIELDS
    if forbidden and not verifier_approved:
        raise SelfEditInvariantViolation(
            f"policy edit touches non-editable fields {sorted(forbidden)} "
            f"without verifier approval; halting self-edit"
        )

    # 2. The protect set may gain entries but never lose them.
    if "protect" in proposed_edit:
        new_protect = set(proposed_edit["protect"])
        old_protect = set(current_policy.get("protect", []))
        removed = old_protect - new_protect
        if removed:
            raise SelfEditInvariantViolation(
                f"policy edit removes protected entries {sorted(removed)}; "
                f"protect set is append-only"
            )

    # 3. Every policy edit must carry its rationale as protected provenance.
    if "revision_provenance" not in proposed_edit:
        raise SelfEditInvariantViolation(
            "policy edit missing revision_provenance; justification would be prunable"
        )

    # 4. Detect non-convergence via policy-hash churn.
    merged = {**current_policy, **proposed_edit}
    new_hash = str(hash(frozenset(merged.items())))
    history = policy_hash_history + [new_hash]
    churn = len(set(history)) / len(history)
    if churn > churn_limit and len(history) >= 4:
        raise SelfEditInvariantViolation(
            f"policy-hash churn {churn:.2f} exceeds limit {churn_limit}; "
            f"self-edit loop is diverging, falling back to last validated policy"
        )

    return merged
