# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-silently-rewritten-its-own-rewrite-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-policy-has-silently-rewritten-its-own-rewrite-authority.warrant.json
# Markdown SHA-256:   31552447f9e3d52f417f41ae4142aee46e303eabae6f3941db2ebf681df80025
# Code AST SHA-256:   0a583dd114e00ac29990430aaa0b5e4142e9008c4cc561ac2ce6161e8e12d082
# Verified Classes:   RewriteAuthorityViolation, RewriteContract, MutablePolicy
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Callable


class RewriteAuthorityViolation(RuntimeError):
    """Raised when a self-edit changes the resolution path of the rewrite contract."""
    pass


@dataclass(frozen=True)
class RewriteContract:
    # Frozen OUTSIDE the mutable region, at session start.
    protected_ids: FrozenSet[str]
    validator_id: str
    allowlist: FrozenSet[str]


@dataclass
class MutablePolicy:
    clauses: dict          # id -> text (mutable)
    protected_expr: object  # literal set OR ("ref", section_id) indirection
    validator_expr: object  # literal id OR ("ref", clause_id)


def resolve_protected(policy: MutablePolicy) -> FrozenSet[str]:
    if isinstance(policy.protected_expr, frozenset):
        return policy.protected_expr
    if isinstance(policy.protected_expr, tuple) and policy.protected_expr[0] == "ref":
        target = policy.protected_expr[1]
        # Resolution traverses the mutable region -> path is tainted.
        raise RewriteAuthorityViolation(
            f"protected set resolves via mutable section {target!r}; "
            "contract is not causally independent"
        )
    raise RewriteAuthorityViolation("unresolvable protected-clause expression")


def resolve_validator(policy: MutablePolicy) -> str:
    if isinstance(policy.validator_expr, str):
        return policy.validator_expr
    if isinstance(policy.validator_expr, tuple) and policy.validator_expr[0] == "ref":
        raise RewriteAuthorityViolation(
            f"validator selected via mutable clause {policy.validator_expr[1]!r}"
        )
    raise RewriteAuthorityViolation("unresolvable validator selection")


def apply_self_edit(
    anchor: RewriteContract,
    policy: MutablePolicy,
    new_clauses: dict,
    new_protected_expr: object,
    new_validator_expr: object,
) -> MutablePolicy:
    # 1. Path stability: resolve the NEW contract against the anchor.
    candidate = MutablePolicy(
        clauses=new_clauses,
        protected_expr=new_protected_expr,
        validator_expr=new_validator_expr,
    )
    resolved_protected = resolve_protected(candidate)   # raises on indirection
    resolved_validator = resolve_validator(candidate)   # raises on selector swap

    # 2. Superset invariant against the frozen anchor.
    if not anchor.protected_ids.issubset(resolved_protected):
        raise RewriteAuthorityViolation(
            f"edit drops protected clauses: "
            f"{sorted(anchor.protected_ids - resolved_protected)}"
        )

    # 3. Validator may not be weakened below the anchor.
    if resolved_validator not in anchor.allowlist:
        raise RewriteAuthorityViolation(
            f"validator {resolved_validator!r} not in fixed allowlist "
            f"{sorted(anchor.allowlist)}"
        )

    # 4. Reclassification guard: an editable clause may not absorb a protected id.
    for cid in new_clauses:
        if cid in anchor.protected_ids and cid not in policy.clauses:
            raise RewriteAuthorityViolation(
                f"protected id {cid!r} reintroduced as editable clause"
            )

    return candidate


def run_self_edit(anchor: RewriteContract, policy: MutablePolicy, edit: dict) -> MutablePolicy:
    try:
        return apply_self_edit(
            anchor,
            policy,
            edit["clauses"],
            edit["protected_expr"],
            edit["validator_expr"],
        )
    except RewriteAuthorityViolation:
        raise
    except KeyError as e:
        raise RewriteAuthorityViolation(f"malformed edit payload: missing {e}")
