# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-summarizes-its-own-context-in-place-and-the-summary-inherits-the-discarded-span-s-salience-weights.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-summarizes-its-own-context-in-place-and-the-summary-inherits-the-discarded-span-s-salience-weights.warrant.json
# Markdown SHA-256:   40a648f28379440f024a38bf1821c28c27886226ba7acdef7457586d33fb5b97
# Code AST SHA-256:   c2a60eeb57e150dd3c2ea4a8463715d181943e901c00b68916f0fe086902a309
# Verified Classes:   StaleSalienceEvictionError, FoldRecord, SelfEditingContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleSalienceEvictionError(RuntimeError):
    """Raised when a query targets a field path that was evicted under a
    different subgoal than the one currently active, and the original
    bytes are no longer reachable for re-expansion."""
    pass


class FoldRecord:
    def __init__(self, subgoal, dropped_paths, handle):
        self.subgoal = subgoal
        self.dropped_paths = set(dropped_paths)
        self.handle = handle  # None if bytes were truly overwritten


class SelfEditingContext:
    def __init__(self):
        self.folds = []
        self.live_paths = set()

    def fold(self, subgoal, keep_paths, drop_paths, handle):
        # A fold is only reversible if we retain a handle to the originals.
        self.folds.append(FoldRecord(subgoal, drop_paths, handle))
        self.live_paths = set(keep_paths)

    def query(self, active_subgoal, path):
        if path in self.live_paths:
            return ("live", path)
        for rec in reversed(self.folds):
            if path in rec.dropped_paths:
                if rec.subgoal != active_subgoal:
                    if rec.handle is None:
                        # Evicted under a different goal, bytes gone: unrecoverable.
                        raise StaleSalienceEvictionError(
                            f"path {path!r} evicted under subgoal {rec.subgoal!r}, "
                            f"queried under {active_subgoal!r}, no re-expansion handle"
                        )
                    # Stale summary, but bytes are addressable: force re-expansion.
                    return ("re_expand", rec.handle, path)
        return ("absent", path)


def reconcile(ctx, active_subgoal, required_paths):
    out = {}
    for p in required_paths:
        status = ctx.query(active_subgoal, p)
        if status[0] == "re_expand":
            # Pull originals back into the window before reasoning over them.
            out[p] = ("from_handle", status[1], status[2])
        elif status[0] == "absent":
            raise StaleSalienceEvictionError(
                f"required path {p!r} never observed and not in any fold manifest"
            )
        else:
            out[p] = status
    return out
