# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruning-pass-deletes-its-own-policy-preamble.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-the-pruning-pass-deletes-its-own-policy-preamble.warrant.json
# Markdown SHA-256:   258a45b445542a7ae628080f46b7787739b8562aefd9ca751fb22e74f47db453
# Code AST SHA-256:   211c0db5add74743c95004f41a1ab2a85473f52597c48716af7bb43509e94bde
# Verified Classes:   PolicyPreambleDeletionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PolicyPreambleDeletionError(RuntimeError):
    """Raised when a self-editing context rewrite would drop protected policy content."""
    pass


PROTECTED_PREFIX_TOKENS = 620  # reserved, non-addressable region
SELF_PROTECTION_CLAUSE = "never_drop_this_rubric"


def apply_rewrite(context: list[dict], proposed_drop: set[int],
                  immutable_policy: dict) -> list[dict]:
    """
    Apply a self-editing rewrite pass, enforcing the non-addressable policy region.

    context: mutable buffer, index 0..N
    proposed_drop: indices the salience scorer wants to delete
    immutable_policy: re-materialized from external store each pass
    """
    protected = set(range(PROTECTED_PREFIX_TOKENS))

    # Invariant 1: protected region is non-addressable.
    violated = proposed_drop & protected
    if violated:
        raise PolicyPreambleDeletionError(
            f"rewrite attempted to drop {len(violated)} protected token indices "
            f"(e.g. {sorted(violated)[:5]}); policy region is non-addressable"
        )

    # Invariant 2: post-state must contain the self-protection clause.
    post_state = [seg for i, seg in enumerate(context) if i not in proposed_drop]
    has_clause = any(
        seg.get("content") == SELF_PROTECTION_CLAUSE for seg in post_state
    )
    if not has_clause:
        raise PolicyPreambleDeletionError(
            "post-rewrite state lacks self-protection clause; "
            "refusing to emit an unconstrained rewriter"
        )

    # Invariant 3: re-materialize policy from immutable source, never carry forward.
    rebuilt = [immutable_policy] + post_state
    return rebuilt


def rewrite_loop(context: list[dict], immutable_policy: dict,
                 scorer, max_passes: int = 8) -> list[dict]:
    for pass_no in range(max_passes):
        proposed = scorer(context)  # salience-weighted drop set
        try:
            context = apply_rewrite(context, proposed, immutable_policy)
        except PolicyPreambleDeletionError as e:
            # hard halt: do not continue with degraded constraints
            raise PolicyPreambleDeletionError(
                f"pass {pass_no} aborted: {e}"
            ) from e
    return context
