# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-edit-provenance-is-not-preserved-across-a-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-the-edit-provenance-is-not-preserved-across-a-checkpoint.warrant.json
# Markdown SHA-256:   da0e71bbbc5555a738e266484c33277d3439d6966fd0a4cc2f374e365df12a3b
# Code AST SHA-256:   733aff3bbdef19a537b156f1fdc8ad187b4bc927b67658012290fed14d0f2396
# Verified Classes:   ProvenanceIncompleteError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceIncompleteError(RuntimeError):
    """Raised when a checkpoint's buffer cannot be safely resumed because
    synthesized spans lack provenance records or hard-constraint authority
    was lost during a self-edit."""


class Span:
    def __init__(self, span_id, text, authority, source_ids=None):
        self.span_id = span_id
        self.text = text
        # authority in {"observed", "derived", "synthesized"}
        self.authority = authority
        self.source_ids = source_ids or []


def apply_rewrite(buffer, rewrite):
    """Apply a model-generated rewrite in place, emitting a provenance record.
    rewrite = {"target_span_ids": [...], "new_text": str, "mutation_type": str}
    Returns (new_buffer, ledger_entry). Refuses to demote hard constraints."""
    targets = [s for s in buffer if s.span_id in rewrite["target_span_ids"]]
    if not targets:
        raise ProvenanceIncompleteError(
            f"rewrite targets {rewrite['target_span_ids']} not present in buffer"
        )
    # Authority floor: a hard constraint may be rephrased but not demoted.
    if any(t.authority == "hard_constraint" for t in targets):
        if "never" not in rewrite["new_text"].lower():
            raise ProvenanceIncompleteError(
                "rewrite would drop a hard-constraint predicate; refusing in-place mutation"
            )
    new_span = Span(
        span_id=f"rw_{rewrite['mutation_type']}_{len(buffer)}",
        text=rewrite["new_text"],
        authority="synthesized",
        source_ids=[t.span_id for t in targets],
    )
    retained = [s for s in buffer if s.span_id not in rewrite["target_span_ids"]]
    ledger_entry = {
        "mutation": rewrite["mutation_type"],
        "sources": new_span.source_ids,
        "result": new_span.span_id,
        "authority_class": new_span.authority,
        "reversible": True,  # sources retained in cold storage keyed by span_id
    }
    return retained + [new_span], ledger_entry


def resume_from_checkpoint(checkpoint):
    """Reconstruct authority map before any action. Raises if provenance is
    incomplete: synthesized spans with no source records, or a buffer that
    claims hard constraints were never present."""
    buffer = checkpoint["buffer"]
    ledger = checkpoint.get("ledger", [])
    known_ids = {s.span_id for s in buffer}
    for entry in ledger:
        for src in entry["sources"]:
            # A source that is neither in-buffer nor in cold storage is a
            # provenance hole: the resumed instance cannot re-derive the span.
            if src not in known_ids and src not in checkpoint.get("cold_storage", {}):
                raise ProvenanceIncompleteError(
                    f"ledger entry {entry['result']} references missing source {src}; "
                    "resume would treat synthesized content as observed"
                )
    for span in buffer:
        if span.authority == "synthesized" and not span.source_ids:
            raise ProvenanceIncompleteError(
                f"synthesized span {span.span_id} has no source provenance; "
                "authority cannot be reconstructed on resume"
            )
    return buffer, ledger
