# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-promotes-episodic-memory-to-semantic-before-its-ttl-window-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-promotes-episodic-memory-to-semantic-before-its-ttl-window-closes.warrant.json
# Markdown SHA-256:   0af02a90056fd8cee91ed3dcc25451e73afd9270a706d7551ddbc758843ac629
# Code AST SHA-256:   ba3b15d004ee1a4bc2914d9bfc99072f63a8c695a609cbb74a32a478c6707217
# Verified Classes:   EpisodicPromotionViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EpisodicPromotionViolation(RuntimeError):
    """Raised when a retrieval-triggered promotion would extend a record's
    effective TTL beyond its sources' remaining lifetime, or when a distilled
    semantic claim drops validity-bearing fields."""
    pass


VALIDITY_FIELDS = {"error_class", "observed_at", "source_instance", "task_id"}


def promote_episodic_to_semantic(
    episodic_record: dict,
    distilled_claim: dict,
    now: float,
    corroborating_sources: list[dict],
) -> dict:
    """Promote an episodic record to semantic ONLY if the resulting claim
    cannot outlive its evidence and remains re-evaluatable."""
    source_ttl_remaining = episodic_record["expires_at"] - now
    if source_ttl_remaining <= 0:
        raise EpisodicPromotionViolation(
            f"record {episodic_record['id']} already expired; consolidate, do not promote"
        )

    # Rule 1: distilled claim must retain validity-bearing fields.
    missing = VALIDITY_FIELDS - set(distilled_claim.keys())
    if missing:
        raise EpisodicPromotionViolation(
            f"distilled claim drops validity fields {sorted(missing)}; "
            f"downstream readers cannot re-evaluate staleness"
        )

    # Rule 2: promotion must be corroborated across independent sources.
    independent = {
        s["task_id"] for s in corroborating_sources
        if s["task_id"] != episodic_record["task_id"]
    }
    if not independent:
        raise EpisodicPromotionViolation(
            f"no corroboration from an independent task_id for {episodic_record['id']}; "
            f"single-source promotion selects for near-death transients"
        )

    # Rule 3: semantic TTL is bounded by the minimum remaining source TTL.
    all_remaining = [source_ttl_remaining] + [
        s["expires_at"] - now for s in corroborating_sources
    ]
    semantic_ttl = min(all_remaining)
    if semantic_ttl <= 0:
        raise EpisodicPromotionViolation(
            "a corroborating source has already expired; recompute corroboration"
        )

    return {
        **distilled_claim,
        "expires_at": now + semantic_ttl,
        "derived_from": [episodic_record["id"]] + [s["id"] for s in corroborating_sources],
        "promotion_kind": "corroborated_scheduled",
    }
