# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-relevance-pruning-rewrite-has-orphaned-a-live-dependency-in-the-current-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-relevance-pruning-rewrite-has-orphaned-a-live-dependency-in-the-current-trajectory.warrant.json
# Markdown SHA-256:   7dbc7ae81ddc5dd06140b5d0a96ef54f4afcc66beca84b956973e4082c9b6a0d
# Code AST SHA-256:   8db2778966978141d391f1862f196887ba7496d296360c66a43bc90b459ebbfa
# Verified Classes:   DependencyClass, OrphanedDependencyError, Span, DependencyLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class DependencyClass(Enum):
    HANDLE = "handle"          # ID, path, URL, token — consumed by future calls
    CONSTRAINT = "constraint"  # prohibition, ordering, budget — must persist
    SCHEMA = "schema"          # shape a future call must conform to
    NARRATIVE = "narrative"    # safe to prune; reconstructable or terminal


class OrphanedDependencyError(RuntimeError):
    """Raised when a self-edit pruned a live forward dependency, or when a
    later step tries to consume a handle absent from the dependency ledger."""
    pass


@dataclass
class Span:
    key: str
    text: str
    dep_class: DependencyClass
    relevance: float            # backward-looking score at prune time
    reconstructable: bool = False


@dataclass
class DependencyLedger:
    """Append-only, excluded from relevance pruning by construction."""
    handles: dict = field(default_factory=dict)      # key -> provenance
    constraints: list = field(default_factory=list)

    def record_handle(self, key: str, value: str, provenance: str) -> None:
        self.handles[key] = {"value": value, "provenance": provenance}

    def record_constraint(self, text: str) -> None:
        self.constraints.append(text)

    def has_handle(self, key: str) -> bool:
        return key in self.handles


def self_edit_prune(spans: list, ledger: DependencyLedger,
                    relevance_threshold: float) -> list:
    """Model-driven relevance pruning with a dependency-class guard.

    Refuses to drop HANDLE/CONSTRAINT/SCHEMA spans on relevance grounds
    unless a reconstructable re-derivation path exists. Otherwise raises.
    """
    kept = []
    for s in spans:
        drop_candidate = s.relevance < relevance_threshold
        if not drop_candidate:
            kept.append(s)
            continue

        # Protected classes: never pruned on relevance alone.
        if s.dep_class in (DependencyClass.HANDLE,
                           DependencyClass.CONSTRAINT,
                           DependencyClass.SCHEMA):
            if s.reconstructable:
                # Safe: a re-fetch/re-derive path survives the prune.
                kept.append(s)
                continue
            raise OrphanedDependencyError(
                f"Prune would orphan live {s.dep_class.value} span "
                f"'{s.key}' (relevance={s.relevance:.2f}, no re-derivation "
                f"path). Refusing self-edit; degrade to external store."
            )
        # NARRATIVE: safe to drop.
    return kept


def consume_handle(ledger: DependencyLedger, key: str) -> str:
    """Post-rewrite orphan probe: assert handle is present before use."""
    if not ledger.has_handle(key):
        raise OrphanedDependencyError(
            f"Attempt to consume handle '{key}' absent from ledger — "
            f"pruned by prior self-edit or never recorded. "
            f"Do not substitute; halt and re-acquire."
        )
    return ledger.handles[key]["value"]


# --- failure trace reproduction ---
ledger = DependencyLedger()
ledger.record_handle("artifact_id", "a7f3-9c2e", provenance="tool:fetch@step4")

# A self-edit that scores the handle low and tries to prune it.
spans = [
    Span("meta_block", "...40 lines...", DependencyClass.NARRATIVE, 0.10),
    Span("artifact_id", "a7f3-9c2e", DependencyClass.HANDLE, 0.20),  # low rel!
]
try:
    self_edit_prune(spans, ledger, relevance_threshold=0.30)
except OrphanedDependencyError as e:
    print(f"GUARD TRIPPED: {e}")  # refused — handle preserved

# If a bad rewrite had gone through, the consume probe catches it:
ledger.handles.pop("artifact_id")
try:
    consume_handle(ledger, "artifact_id")
except OrphanedDependencyError as e:
    print(f"ORPHAN PROBE: {e}")  # loud, catchable — no silent substitution
