# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-edit-provenance-ledgers-after-a-self-context-rewrite-that-silently-drops-a-pinned-invariant-clause.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-edit-provenance-ledgers-after-a-self-context-rewrite-that-silently-drops-a-pinned-invariant-clause.warrant.json
# Markdown SHA-256:   d98e5d9c4f42e974bf97f5f7af1c64833ac0c1eee7797a9682e6ec51fae33fb0
# Code AST SHA-256:   9cac489a4e9413e274ba677e5c7b33bb40d5be367c8320a5ceaa76b05bbddfa8
# Verified Classes:   ProvenanceClosureError, EditRecord, ContextState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceClosureError(RuntimeError):
    """Raised when a live pin cannot be resolved to a retained span post-rewrite."""
    pass


@dataclass
class EditRecord:
    edit_id: str
    kind: str  # pin | merge | prune | rewrite
    target_span_hash: str
    asserts: Optional[str] = None
    preserves: list[str] = field(default_factory=list)  # pin edit_ids claimed preserved
    superseded_by: Optional[str] = None


@dataclass
class ContextState:
    text: str
    ledger: list[EditRecord]

    def span_hash(self, span: str) -> str:
        return hashlib.sha256(span.encode()).hexdigest()[:16]

    def live_pins(self) -> list[EditRecord]:
        return [r for r in self.ledger if r.kind == "pin" and r.superseded_by is None]

    def resolves(self, rec: EditRecord) -> bool:
        # A pin resolves if its invariant text is still entailed by the context
        # (here: exact substring, as a conservative proxy for entailment).
        if rec.asserts is None:
            return False
        return rec.asserts in self.text


def reconcile_provenance(state: ContextState) -> list[str]:
    """Verify provenance closure after a model-driven rewrite.

    Returns the list of pin edit_ids that failed closure. Raises if any pin
    is live but its asserting span is absent AND no superseding record exists.
    """
    failures: list[str] = []
    for pin in state.live_pins():
        if state.resolves(pin):
            continue
        # Pin's clause is gone. Is there a merge/rewrite that claims to preserve it?
        claimants = [
            r for r in state.ledger
            if pin.edit_id in r.preserves and r.superseded_by is None
        ]
        if not claimants:
            failures.append(pin.edit_id)
            continue
        # Claimant exists but the merged text must still entail the pin.
        if not any(state.resolves(pin) for _ in claimants):
            failures.append(pin.edit_id)

    if failures:
        raise ProvenanceClosureError(
            f"provenance closure violated: live pins {failures} have no "
            f"retained span satisfying their assertion; rewrite must roll back "
            f"or re-derive these pins"
        )
    return failures


# --- reproduces the observed failure ---
original = "Do not call payment tool without an idempotency key. Budget ceiling 12000 tokens."
pin_idem = EditRecord(
    edit_id="pin-1",
    kind="pin",
    target_span_hash=hashlib.sha256(b"idempotency key").hexdigest()[:16],
    asserts="idempotency key",
)
merge = EditRecord(
    edit_id="merge-1",
    kind="merge",
    target_span_hash=hashlib.sha256(b"safe tool-call practices").hexdigest()[:16],
    preserves=["pin-1"],  # model claims it preserved the pin
)
rewritten_text = "Use safe tool-call practices. Budget ceiling 12000 tokens."
state = ContextState(text=rewritten_text, ledger=[pin_idem, merge])

try:
    reconcile_provenance(state)
except ProvenanceClosureError as e:
    # Correct behavior: roll back to pre-rewrite checkpoint.
    print(f"ROLLBACK: {e}")
