# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-its-consolidation-job-is-silently-rewriting-episodic-memory-into-a-semantic-prior-that-contradicts-the-episode-it-w.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-its-consolidation-job-is-silently-rewriting-episodic-memory-into-a-semantic-prior-that-contradicts-the-episode-it-w.warrant.json
# Markdown SHA-256:   f5e82b3a4c36a3457ced5882fb1bde4a2305cf4c8d0ca3f2208b7981a08d59da
# Code AST SHA-256:   fcbd965b1cb545d4a90def72600d6d5ceb271b770e1d1d36ec49c6b9342cfa51
# Verified Classes:   ProvenanceWitnessError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceWitnessError(RuntimeError):
    """Raised when decay would orphan a live semantic assertion from its sole episodic witness."""
    pass


def apply_decay(
    episode: dict,
    live_assertions: list[dict],
    new_weight: float,
    retrieval_threshold: float = 0.05,
    provenance_floor: float = 0.01,
) -> dict:
    dependent = [
        a for a in live_assertions
        if a["provenance_episode_id"] == episode["id"]
        and a["provenance_count"] == 1
    ]

    if dependent and new_weight < retrieval_threshold:
        # Sole-provenance assertion would lose its only retrievable witness.
        # Pin provenance instead of decaying to zero; exclude from retrieval.
        if provenance_floor >= retrieval_threshold:
            raise ProvenanceWitnessError(
                f"provenance_floor {provenance_floor} >= retrieval_threshold "
                f"{retrieval_threshold}; cannot pin without keeping episode retrievable"
            )
        return {
            **episode,
            "retrieval_weight": 0.0,
            "provenance_weight": provenance_floor,
            "pinned_for": [a["id"] for a in dependent],
        }

    if dependent and new_weight < provenance_floor:
        raise ProvenanceWitnessError(
            f"decay to {new_weight} would drop episode {episode['id']} below "
            f"provenance floor while {len(dependent)} assertion(s) depend on it"
        )

    return {**episode, "retrieval_weight": new_weight}
