# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-on-a-stale-salience-score-and-silently-deletes-the-constraint-it-is-about-to-violate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-its-own-context-on-a-stale-salience-score-and-silently-deletes-the-constraint-it-is-about-to-violate.warrant.json
# Markdown SHA-256:   898834ca52fdf352f8dcbd5ef3ebdc78bc4f30e94885084163bcf3df1128d89d
# Code AST SHA-256:   5e26d158e8c40296a0e563b30eb81bf1e50b3cc52568c90af60cdc19da2147c5
# Verified Classes:   ConstraintEvictionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ConstraintEvictionError(RuntimeError):
    """Raised when a pruning pass would evict (or has evicted) a constraint span.

    Constraints are valid until explicitly retracted, never until they stop
    scoring as salient. Any attempt to score-and-drop one is a soundness bug.
    """
    pass


CONSTRAINT = "constraint"
DERIVATIONAL = "derivational"


def classify(span: dict) -> str:
    # Fail closed: unknown -> constraint.
    return span.get("class", CONSTRAINT)


def prune(spans: list[dict], salience_fn, budget: int, manifest: dict) -> list[dict]:
    """Self-edit pass with pinned constraints and an eviction ledger.

    Only DERIVATIONAL spans enter the scored pool. Constraints are pinned
    unconditionally. The manifest records every eviction so the agent can
    later observe the shape of its own amnesia.
    """
    pinned, pool = [], []
    for s in spans:
        (pinned if classify(s) == CONSTRAINT else pool).append(s)

    # Score only the derivational pool.
    scored = sorted(pool, key=salience_fn, reverse=True)

    kept, evicted = [], []
    used = sum(len(s["text"]) for s in pinned)
    for s in scored:
        if used + len(s["text"]) <= budget:
            kept.append(s)
            used += len(s["text"])
        else:
            evicted.append(s)

    # Invariant: no constraint may appear in the eviction set.
    leaked = [s for s in evicted if classify(s) == CONSTRAINT]
    if leaked:
        manifest["constraints_evicted"] = len(leaked)
        raise ConstraintEvictionError(
            f"pruning would drop {len(leaked)} constraint span(s): "
            f"{[s['id'] for s in leaked]} -- halt and re-derive, do not proceed"
        )

    manifest["constraints_evicted"] = 0
    manifest["evicted_ids"] = [s["id"] for s in evicted]
    manifest["evicted_reasons"] = {s["id"]: "low-salience derivational" for s in evicted}
    return pinned + kept


def assert_manifest_clean(manifest: dict) -> None:
    """Call on every subsequent step; a dirty manifest means the context
    can no longer be trusted to bound the agent's actions."""
    if manifest.get("constraints_evicted", 0) != 0:
        raise ConstraintEvictionError(
            "eviction manifest reports dropped constraints; "
            "active context is unsound for further execution"
        )
