# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-salience-scores-and-the-rewrite-is-not-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-salience-scores-and-the-rewrite-is-not-idempotent.warrant.json
# Markdown SHA-256:   c3f9f418925945a84d3e1abe832e2529561792c097f953307997f540c29b68c3
# Code AST SHA-256:   7464e74618e146df5fc38582be13eb264122d9115fa6a4af95102b43b6015244
# Verified Classes:   SalienceRatchetError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SalienceRatchetError(RuntimeError):
    """Raised when a self-editing context policy scores against its own
    derived representation, producing a non-idempotent salience fold."""


def apply_salience_policy(records, scorer, evict_floor=0.15):
    """
    Enforce the invariant: score against immutable originals, store rewrites
    as non-destructive views, evict only into a recoverable cold tier.
    """
    cold_tier = {}
    for rec in records:
        # Guard 1: scoring input must be the original, never the summary.
        if rec.score_input_is_derived:
            raise SalienceRatchetError(
                f"record {rec.id}: scorer is reading derived form "
                f"'{rec.summary[:40]!r}' instead of original; "
                f"salience fold is non-idempotent"
            )

        # Guard 2: a stored score may not outlive its source text.
        if rec.stored_score is not None and rec.stored_score_hash != rec.original_hash:
            raise SalienceRatchetError(
                f"record {rec.id}: stored score {rec.stored_score:.2f} was "
                f"computed against a different original (hash mismatch); "
                f"carrying it forward would ratchet salience downward"
            )

        score = scorer(rec.original)  # pure function of immutable source

        # Guard 3: eviction must be reversible within the task horizon.
        if score < evict_floor:
            cold_tier[rec.original_hash] = rec.original
            rec.evicted = True
        else:
            rec.summary = compress(rec.original)  # view, not overwrite
            rec.stored_score = score
            rec.stored_score_hash = rec.original_hash

    return records, cold_tier


def assert_idempotent(records, scorer, evict_floor=0.15):
    """Running the policy twice must equal running it once."""
    once, _ = apply_salience_policy(records, scorer, evict_floor)
    twice, _ = apply_salience_policy(once, scorer, evict_floor)
    for a, b in zip(once, twice):
        if abs((a.stored_score or 0.0) - (b.stored_score or 0.0)) > 1e-6:
            raise SalienceRatchetError(
                f"record {a.id}: salience drifted {a.stored_score:.3f} -> "
                f"{b.stored_score:.3f} on second pass; policy is not idempotent"
            )
    return True
