# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-in-place-trajectory-rewriting-when-a-self-editing-context-window-mutates-the-prefix-it-is-standing-on.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-in-place-trajectory-rewriting-when-a-self-editing-context-window-mutates-the-prefix-it-is-standing-on.warrant.json
# Markdown SHA-256:   9034552e76f703b8e4bdc1823080c58080e97af4a10af4b9e169387d1a7ba4a2
# Code AST SHA-256:   7683e400142ba6139579091154d02414c92ddedac55c2cb9e355a319a4b35bb0
# Verified Classes:   PrefixConsistencyViolation, RewritePlan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class PrefixConsistencyViolation(RuntimeError):
    """Raised when an in-place rewrite removes a literal that a surviving step reads."""
    pass


@dataclass
class RewritePlan:
    boundary: int                       # steps 1..boundary-1 will be compacted
    remaining_steps: Set[int]           # steps that survive the rewrite
    forward_deps: Dict[int, Set[str]]   # step -> literals its control flow reads
    pinned_literals: Dict[str, str] = field(default_factory=dict)


def check_rewrite_safe(plan: RewritePlan, compacted_literals: Set[str]) -> None:
    """Fail closed if any surviving step reads a literal the rewrite drops."""
    required: Set[str] = set()
    for step in plan.remaining_steps:
        required |= plan.forward_deps.get(step, set())

    unpinned = required - set(plan.pinned_literals) - compacted_literals
    if unpinned:
        raise PrefixConsistencyViolation(
            f"rewrite at boundary {plan.boundary} drops literals "
            f"{sorted(unpinned)} read by surviving steps; "
            f"pin them into the ledger or fall back to append-and-redirect"
        )


def apply_in_place_rewrite(plan: RewritePlan, compacted_literals: Set[str]) -> Dict[str, str]:
    check_rewrite_safe(plan, compacted_literals)
    # Only reached when forward dependency closure is satisfied by pinned literals.
    return dict(plan.pinned_literals)
