# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-summarization-induced-commitment-loss-in-self-editing-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-summarization-induced-commitment-loss-in-self-editing-context-windows.warrant.json
# Markdown SHA-256:   08569327acecbf4c3dbedca3441faf03c7a1b5769d3ea14dea45928e839eec70
# Code AST SHA-256:   3e7cffd322be4cb4170e94731690abbe2bba4c566d3a6561fd0fa5e8a0d5979e
# Verified Classes:   CommitmentGuardLoss
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitmentGuardLoss(RuntimeError):
    """Raised when a live commitment's invalidation guard is missing at re-deliberation time."""
    pass


def prune_context(spans, budget):
    kept, dropped = [], []
    for span in spans:
        # Commitment spans are never scored; they are retained as an atomic unit.
        if span.kind == "commitment":
            if span.guard is None:
                raise CommitmentGuardLoss(
                    f"commitment {span.id!r} has no guard; refusing to prune a guardless commitment"
                )
            kept.append(span)
        elif span.kind == "narrative" and span.score < budget.threshold:
            dropped.append(span)
        else:
            kept.append(span)
    return kept, dropped


def redeliberate(candidate, commitment_log):
    # Re-proposing a rejected alternative requires its guard record to be present.
    for c in commitment_log:
        if candidate.alternative_id in c.rejects:
            if c.guard is None:
                raise CommitmentGuardLoss(
                    f"cannot re-propose {candidate.alternative_id!r}: "
                    f"rejection by {c.id!r} has no recorded guard; re-derive before acting"
                )
            if not c.guard.holds(candidate.evidence):
                return candidate  # guard discharged: re-proposal is now legitimate
            raise CommitmentGuardLoss(
                f"re-proposal of {candidate.alternative_id!r} blocked: guard {c.guard.predicate!r} still holds"
            )
    return candidate
