# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-diff-based-context-rewrite-rather-than-roll-it-back.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-diff-based-context-rewrite-rather-than-roll-it-back.warrant.json
# Markdown SHA-256:   04c2c5d37495d28b93e30062de5a767ff78aa02beb2363b487692c60a0c04c1f
# Code AST SHA-256:   1ea3bce5f391aa61588687f0ce296f838dc92f089ce23c3bf78b206caf719c39
# Verified Classes:   UnrollbackableRewriteError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnrollbackableRewriteError(RuntimeError):
    """Raised when a context diff would destroy the evidence needed to adjudicate it."""
    pass


def apply_context_diff(context, diff, decision_log):
    """
    context: dict[span_id -> Span], each Span has .text, .origin in {"tool","user","agent"},
             and optional .derived_from (tuple of span_ids).
    diff:    {"removes": set[span_id], "adds": list[Span], "rationale_refs": set[span_id]}
    decision_log: append-only list of dicts describing why diffs were emitted.
    """
    removes = set(diff["removes"])
    refs = set(diff["rationale_refs"])

    # Boundary 1: the diff cites a span it is about to delete. Self-justifying.
    self_justifying = removes & refs
    if self_justifying:
        raise UnrollbackableRewriteError(
            f"diff removes spans it cites as justification: {sorted(self_justifying)}; "
            f"rollback would restore bytes but not the trigger. Refuse and defer to external store."
        )

    # Boundary 2: replacing source spans with agent-authored spans without provenance links.
    for new_span in diff["adds"]:
        if new_span.origin == "agent" and not getattr(new_span, "derived_from", None):
            replaced_sources = [
                sid for sid in removes
                if context[sid].origin in ("tool", "user")
            ]
            if replaced_sources:
                raise UnrollbackableRewriteError(
                    f"agent-authored span {new_span!r} replaces source spans "
                    f"{sorted(replaced_sources)} with no derived_from link; "
                    f"provenance would be lost irrecoverably."
                )

    # Boundary 3: the trigger for this rewrite lives inside the rewritten region.
    trigger_spans = {entry["trigger_span"] for entry in decision_log if "trigger_span" in entry}
    if removes & trigger_spans:
        raise UnrollbackableRewriteError(
            f"diff removes its own trigger spans {sorted(removes & trigger_spans)}; "
            f"post-rollback agent would regenerate the same diff. Refuse."
        )

    # Safe: apply, recording provenance.
    new_context = {sid: span for sid, span in context.items() if sid not in removes}
    for new_span in diff["adds"]:
        new_context[new_span.id] = new_span
    decision_log.append({
        "applied": True,
        "removes": sorted(removes),
        "rationale_refs": sorted(refs),
    })
    return new_context
