# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-relevance-scored-pruning-decisions-when-the-scoring-model-shares-the-context-window-with-the-memor.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-its-own-relevance-scored-pruning-decisions-when-the-scoring-model-shares-the-context-window-with-the-memor.warrant.json
# Markdown SHA-256:   b715e626712bd552ea7d1632daecf5103201ce8424bea8f6cc5972ac75440b61
# Code AST SHA-256:   e86a04758b56fab3ae6f5fad25d1131bfb0696e8c9735c54d6d048827e7a98ac
# Verified Classes:   CoupledScoringError, Segment, PruneDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class CoupledScoringError(RuntimeError):
    """Raised when an in-band relevance score cannot be trusted because the
    scored item's context was contaminated by co-present candidates."""


@dataclass
class Segment:
    seg_id: str
    text: str
    reconstructible: bool          # recoverable from external source of truth
    pinned: bool = False
    refs: set[str] = field(default_factory=set)  # IDs of other segments it references


@dataclass
class PruneDecision:
    seg_id: str
    inband_score: float
    isolated_score: float | None
    action: str                    # "prune" | "keep" | "pinned" | "restore"


COUPLING_TOLERANCE = 0.15


def _hash(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()[:12]


def self_edit(
    segments: list[Segment],
    goal: str,
    inband_scorer: Callable[[str, list[Segment]], float],
    isolated_scorer: Callable[[str, str], float],
    threshold: float = 0.3,
) -> list[PruneDecision]:
    """Run a self-editing pass with coupling detection.

    inband_scorer(goal, all_segments) -> score of the *last* segment, computed
        with every candidate present (the dangerous, self-referential path).
    isolated_scorer(goal, seg_text) -> score computed with no other candidates.
    """
    decisions: list[PruneDecision] = []

    # Guardrail 1: pin irreconstructible memory before scoring at all.
    for seg in segments:
        if seg.pinned or not seg.reconstructible:
            decisions.append(PruneDecision(seg.seg_id, 1.0, None, "pinned"))

    candidates = [s for s in segments if s.reconstructible and not s.pinned]

    # Detect candidate sets that are jointly load-bearing.
    candidate_ids = {s.seg_id for s in candidates}
    coupled: set[str] = set()
    for seg in candidates:
        if seg.refs & candidate_ids:
            coupled.add(seg.seg_id)
            coupled |= seg.refs & candidate_ids

    for seg in candidates:
        inband = inband_scorer(goal, segments)
        isolated = isolated_scorer(goal, seg.text)

        # Guardrail 2: reject in-band scores on coupled items when they
        # disagree with the context-disjoint score.
        if seg.seg_id in coupled and abs(inband - isolated) > COUPLING_TOLERANCE:
            raise CoupledScoringError(
                f"segment {seg.seg_id} in-band score {inband:.2f} diverges from "
                f"isolated score {isolated:.2f} (tol {COUPLING_TOLERANCE}); "
                f"self-referential pruning is unsound for this candidate set"
            )

        effective = isolated if seg.seg_id in coupled else inband
        action = "prune" if effective < threshold else "keep"
        decisions.append(PruneDecision(seg.seg_id, inband, isolated, action))

    # Guardrail 3: reversibility ledger keyed by content hash.
    for d in decisions:
        if d.action == "prune":
            seg = next(s for s in segments if s.seg_id == d.seg_id)
            _LEDGER[_hash(seg.text)] = seg

    return decisions


_LEDGER: dict[str, Segment] = {}


def restore_if_referenced(seg_id: str, downstream_ref: str) -> Segment:
    """If a downstream step references pruned content, restore and invalidate."""
    for h, seg in _LEDGER.items():
        if seg.seg_id == seg_id or seg_id in seg.text:
            del _LEDGER[h]
            return seg
    raise CoupledScoringError(
        f"downstream reference {downstream_ref!r} targets pruned segment "
        f"{seg_id!r} with no ledger entry; scoring pass is invalid"
    )
