# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-rewritten-context-policy-as-a-lossy-commit-rather-than-an-idempotent-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-rewritten-context-policy-as-a-lossy-commit-rather-than-an-idempotent-compaction.warrant.json
# Markdown SHA-256:   b0a8e80e9a5d5a57284a79d10086fbc989d3ec5c752a9a45f8fb9504d68a9edf
# Code AST SHA-256:   77db224fd18faa8278927d83266cf63aee59c3e0adf3c5f88c06c3a4673304eb
# Verified Classes:   ContextPolicyMutationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContextPolicyMutationError(RuntimeError):
    """Raised when a self-rewrite alters the retention function without a
    staged, versioned, monotone-guarded commit."""
    pass


PINNED_REGION_TOKENS = 400
PROTECTED_PRIORITY_KEYS = {"task_spec", "acceptance_criteria"}


def classify_rewrite(rewrite: dict) -> str:
    """Return 'content_only' or 'function_altering'."""
    function_keys = {
        "retention_priority",
        "budget_split",
        "summarization_instruction",
        "eviction_order",
        "trigger_threshold",
        "policy_block",
    }
    if function_keys & set(rewrite.keys()):
        return "function_altering"
    return "content_only"


def commit_self_rewrite(
    rewrite: dict,
    current_policy: dict,
    pinned_tokens_used: int,
    mutations_this_epoch: int,
) -> dict:
    kind = classify_rewrite(rewrite)

    if kind == "content_only":
        # Idempotent compaction: safe to repeat, no versioning needed.
        return {"mode": "compaction", "applied": rewrite}

    # Function-altering path: transactional commit required.
    if pinned_tokens_used < PINNED_REGION_TOKENS:
        raise ContextPolicyMutationError(
            f"pinned rationale region underfunded "
            f"({pinned_tokens_used}/{PINNED_REGION_TOKENS}); "
            f"mutation would delete its own audit trail"
        )

    if mutations_this_epoch >= 1:
        raise ContextPolicyMutationError(
            "policy mutation rate limit exceeded for this budget epoch; "
            "staging required until next epoch boundary"
        )

    new_priority = rewrite.get("retention_priority", {})
    old_priority = current_policy.get("retention_priority", {})
    for key in PROTECTED_PRIORITY_KEYS:
        if key in new_priority and new_priority[key] < old_priority.get(key, float("inf")):
            raise ContextPolicyMutationError(
                f"monotonicity guard: mutation lowers retention priority of "
                f"protected key '{key}', which is the agent's own failure "
                f"detector; rejecting"
            )

    # Stage, do not apply in place; effective at next epoch boundary.
    return {
        "mode": "staged_commit",
        "staged_policy": rewrite,
        "effective_at": "next_epoch_boundary",
        "version": current_policy.get("version", 0) + 1,
    }
