# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-mid-trajectory-and-silently-invalidates-the-provenance-of-an-already-committed-plan-step.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-mid-trajectory-and-silently-invalidates-the-provenance-of-an-already-committed-plan-step.warrant.json
# Markdown SHA-256:   746972d178d5e3e046bba1e8b3f6fc7d7075e2a654f400ef8ff9693b1c67b1d8
# Code AST SHA-256:   3f74bf028373f382b8bbda08d725947b5befca96fefd27aa98f2588fd378ea96
# Verified Classes:   ProvenanceGapError, PlanStep, RewriteProposal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceGapError(RuntimeError):
    """Raised when a context rewrite would leave a committed plan step
    standing on a warrant that the rewrite evicts without marking."""
    pass


@dataclass
class PlanStep:
    step_id: str
    text: str
    committed: bool
    warrant_span_id: Optional[str]  # context span / tool-result ID justifying the step
    warrant_evicted: bool = False


@dataclass
class RewriteProposal:
    surviving_span_ids: set[str] = field(default_factory=set)
    # spans the rewrite keeps; everything else is evicted


def check_rewrite_preserves_provenance(
    steps: list[PlanStep],
    proposal: RewriteProposal,
) -> None:
    """Enforce: committed(step) => resolvable(warrant) or evicted_marker(step).

    Raises ProvenanceGapError if any committed step would survive the rewrite
    with its warrant evicted and no eviction marker set.
    """
    violations: list[str] = []
    for step in steps:
        if not step.committed:
            continue
        if step.warrant_span_id is None:
            # A committed step with no recorded warrant is already a gap;
            # the rewrite cannot be blamed, but it must not paper over it.
            if not step.warrant_evicted:
                violations.append(
                    f"{step.step_id}: committed with no warrant handle and no eviction marker"
                )
            continue
        warrant_survives = step.warrant_span_id in proposal.surviving_span_ids
        if not warrant_survives and not step.warrant_evicted:
            violations.append(
                f"{step.step_id}: committed; warrant span "
                f"{step.warrant_span_id!r} evicted by rewrite with no marker"
            )

    if violations:
        raise ProvenanceGapError(
            "rewrite would create provenance gap(s): " + "; ".join(violations)
        )


def apply_rewrite(
    steps: list[PlanStep],
    proposal: RewriteProposal,
) -> list[PlanStep]:
    """Apply a rewrite only if provenance is preserved; otherwise refuse
    and demote offending steps to provisional for re-derivation."""
    try:
        check_rewrite_preserves_provenance(steps, proposal)
    except ProvenanceGapError:
        # Refuse the rewrite wholesale; demote is the caller's decision.
        raise
    for step in steps:
        if (
            step.committed
            and step.warrant_span_id is not None
            and step.warrant_span_id not in proposal.surviving_span_ids
        ):
            # Only reachable if warrant_evicted was already True; keep marker.
            step.warrant_evicted = True
    return steps


# --- failure trace reproduction ---

steps = [
    PlanStep(
        step_id="S3",
        text="return MappingProxyType from load_config(); callers must not mutate",
        committed=True,
        warrant_span_id="turn4.loader_aliasing_observation",
    ),
]
# Rewrite keeps the plan text but evicts the turn-4 observation span.
proposal = RewriteProposal(surviving_span_ids={"turn5.plan_summary"})

apply_rewrite(steps, proposal)  # raises ProvenanceGapError
