# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-self-editing-context-policies-have-silently-corrupted-an-agent-s-working-set.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-self-editing-context-policies-have-silently-corrupted-an-agent-s-working-set.warrant.json
# Markdown SHA-256:   b1bb29cd13c1530848475e93210adbca0e3a85ff88766b1246c94386023df0dd
# Code AST SHA-256:   8ba967f279c2e655cf04122133819b3a341481ca40a5789a153a1a850a80925f
# Verified Classes:   ContextErasureError, Segment
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ContextErasureError(RuntimeError):
    """Raised when a self-editing pass produces a rewrite whose provenance
    cannot be re-resolved, i.e. a claim that is unfalsifiable by construction."""


class Segment:
    def __init__(self, seg_id, text, score, source_id=None,
                 constraint_bearing=False, assertiveness=0.5):
        self.seg_id = seg_id
        self.text = text
        self.score = score
        self.source_id = source_id          # None for original segments
        self.constraint_bearing = constraint_bearing
        self.assertiveness = assertiveness  # 0..1, higher = more certain


def apply_self_edit(live_set, edited_set, evicted_ids, rewrite_band=(0.3, 0.7)):
    """Validate a model-driven edit pass before committing it to the working set.

    live_set:    dict[seg_id -> Segment] currently resident
    edited_set:  dict[seg_id -> Segment] the pass wants to replace into the set
    evicted_ids: set of seg_ids the pass removes
    """
    lo, hi = rewrite_band
    for seg_id, new_seg in edited_set.items():
        old = live_set.get(seg_id)
        if old is None:
            raise ContextErasureError(
                f"rewrite target {seg_id} not resident; cannot verify provenance"
            )

        # 1. Constraint-bearing segments must never be rewritten.
        if old.constraint_bearing:
            raise ContextErasureError(
                f"segment {seg_id} is constraint-bearing and was rewritten; "
                f"original: {old.text!r} -> surrogate: {new_seg.text!r}"
            )

        # 2. Provenance must survive the same pass that rewrites.
        if new_seg.source_id is not None and new_seg.source_id in evicted_ids:
            raise ContextErasureError(
                f"rewrite of {seg_id} orphans source {new_seg.source_id}: "
                f"source evicted in the same pass -> unfalsifiable claim"
            )
        if new_seg.source_id is None and old.source_id is not None:
            raise ContextErasureError(
                f"rewrite of {seg_id} dropped provenance link to {old.source_id}"
            )

        # 3. Rewrites may not inflate assertiveness (hedge must survive).
        if new_seg.assertiveness > old.assertiveness + 1e-9:
            raise ContextErasureError(
                f"rewrite of {seg_id} inflated assertiveness "
                f"{old.assertiveness:.2f} -> {new_seg.assertiveness:.2f}; "
                f"compression manufactured confidence"
            )

        # 4. Middle-band rewrites are only legal if the source is pinned live.
        if lo <= old.score <= hi and new_seg.source_id not in live_set:
            raise ContextErasureError(
                f"middle-band segment {seg_id} (score={old.score:.2f}) rewritten "
                f"without a live pinned source; re-validation impossible"
            )

    return edited_set
