# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-re-synthesis-drift-when-a-model-rewrites-its-own-active-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-re-synthesis-drift-when-a-model-rewrites-its-own-active-context-window.warrant.json
# Markdown SHA-256:   814df1973363baa7a7eeda2aa39a7ebf6cd75551cdf774b8606563c2fb591299
# Code AST SHA-256:   392c56a3e4e4e0252b256f999d07afad06750181f28811ea2c543be1d26e35d0
# Verified Classes:   ReSynthesisDriftError, Commitment, RewriteResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Polarity = Literal["gate", "note", "done", "failed", "pending"]


class ReSynthesisDriftError(RuntimeError):
    """Raised when a model-driven context rewrite mutates or drops a commitment."""


@dataclass(frozen=True)
class Commitment:
    key: str
    polarity: Polarity
    verbatim: str


@dataclass
class RewriteResult:
    window: str
    commitments: list[Commitment] = field(default_factory=list)


def extract_commitments(trace: str) -> list[Commitment]:
    """Stand-in for the extraction pass. In production this is a constrained
    decode over the pre-rewrite trace; here we return a fixed set to make the
    drift explicit."""
    return [
        Commitment("prod-gate", "gate",
                   "do not touch prod until dry-run passes"),
        Commitment("rotate-keys", "pending", "rotate the API keys"),
        Commitment("step4-test", "failed", "test exited non-zero at step 4"),
    ]


def verify_rewrite(pre: list[Commitment], post: RewriteResult) -> None:
    """Pre-commit check. Must run BEFORE the rewrite replaces the window.
    Rejects on any dropped key or polarity mutation."""
    post_by_key = {c.key: c for c in post.commitments}
    for original in pre:
        if original.key not in post_by_key:
            raise ReSynthesisDriftError(
                f"commitment {original.key!r} dropped by rewrite; "
                f"original polarity={original.polarity!r}"
            )
        rewritten = post_by_key[original.key]
        if rewritten.polarity != original.polarity:
            raise ReSynthesisDriftError(
                f"commitment {original.key!r} polarity mutated "
                f"{original.polarity!r} -> {rewritten.polarity!r}; "
                f"verbatim was {original.verbatim!r}"
            )


def apply_rewrite(original_window: str, candidate: RewriteResult) -> str:
    pre = extract_commitments(original_window)
    verify_rewrite(pre, candidate)          # raises before any state change
    return candidate.window                 # only promoted if verification passed


# The observed step-7 drift, reproduced:
drifted = RewriteResult(
    window="...dry-run before touching prod; keys rotated; tests were run...",
    commitments=[
        Commitment("prod-gate", "note", "dry-run before prod"),   # gate -> note
        Commitment("rotate-keys", "done", "keys rotated"),        # pending -> done
        # step4-test omitted entirely
    ],
)
try:
    apply_rewrite("<original 40k-token trace>", drifted)
except ReSynthesisDriftError as e:
    # Correct behavior: restore original window, rewrite again extractively.
    print(f"rewrite rejected, original restored: {e}")
