# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-self-edited-context-against-the-pre-edit-transcript-when-the-rewrite-is-lossy-but-authoritative.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-self-edited-context-against-the-pre-edit-transcript-when-the-rewrite-is-lossy-but-authoritative.warrant.json
# Markdown SHA-256:   65bee8fe2050f8dc0810412d4f4d13b3fd6b96e71a9a436378a727e768fe5e0c
# Code AST SHA-256:   aeedfbb0371c929c0f8e7a6ca13d07eeb450700e1ee3bf45e4c51b2889752075
# Verified Classes:   ObligationOrphanError, Obligation, RewriteProposal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ObligationOrphanError(RuntimeError):
    """Raised when a context rewrite drops a commitment still owed by an unexecuted step."""


@dataclass(frozen=True)
class Obligation:
    step_id: int
    kind: str          # "non_idempotent", "forbidden_op", "ordering", "pending_confirm"
    target: str


@dataclass
class RewriteProposal:
    narrative: str
    declared_obligations: FrozenSet[Obligation]
    executed_through_step: int


def admit_rewrite(
    pre_obligations: FrozenSet[Obligation],
    proposal: RewriteProposal,
    pending_steps: FrozenSet[int],
) -> FrozenSet[Obligation]:
    """
    Admit a self-edited context as authoritative only if every obligation
    attached to a still-pending step survives the rewrite.
    """
    required = frozenset(
        o for o in pre_obligations if o.step_id in pending_steps
    )
    surviving = frozenset(
        o for o in required if o in proposal.declared_obligations
    )
    orphaned = required - surviving

    if orphaned:
        # The rewrite is internally coherent but has dropped binding force
        # for work still owed. Refuse to mark it authoritative.
        raise ObligationOrphanError(
            "rewrite dropped obligations for pending steps: "
            + ", ".join(
                f"step {o.step_id}:{o.kind}:{o.target}" for o in sorted(orphaned, key=lambda x: (x.step_id, x.kind))
            )
            + f"; executed_through_step={proposal.executed_through_step}"
        )

    return proposal.declared_obligations
