# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-poisoned-memory-write-before-the-semantic-distillation-pass-rather-than-after-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-poisoned-memory-write-before-the-semantic-distillation-pass-rather-than-after-it.warrant.json
# Markdown SHA-256:   796bf53e9c90f574e878be10d9ec77524f731269c5d3b739474599903a7f920b
# Code AST SHA-256:   2c3d7f6ce9f5e6d602ba1c60f7e9676b7367313c9cf6114c58b620962c3dfa56
# Verified Classes:   DistillQuarantineOrderError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DistillQuarantineOrderError(RuntimeError):
    """Raised when a poisoned episode reaches the semantic store because
    quarantine ran after distillation instead of before it."""
    pass


TRUSTED_ORIGINS = frozenset({"attested", "config_read", "user_direct"})


def select_distill_inputs(episodes, *, distill_interval_hours=24):
    """Select episodes eligible for semantic distillation.

    Invariant: untrusted episodes are NEVER merged into a trusted summary.
    They are routed to a separate advisory partition, or excluded entirely.
    """
    trusted, advisory = [], []
    for ep in episodes:
        if ep.get("quarantined"):
            continue
        if ep["origin"] in TRUSTED_ORIGINS and ep.get("trust") == "trusted":
            trusted.append(ep)
        else:
            advisory.append(ep)
    return trusted, advisory


def distill(episodes, semantic_store, *, now_hours_since_last_run):
    if now_hours_since_last_run > 24:
        # Detection deadline blown: poison may already be laundered.
        raise DistillQuarantineOrderError(
            f"distill window exceeded ({now_hours_since_last_run}h > 24h); "
            "poisoned episodes may have bypassed pre-distill detection"
        )

    trusted, advisory = select_distill_inputs(episodes)

    # Pre-distill detection gate: runs BEFORE any summarization.
    for ep in trusted:
        if ep.get("injection_score", 0.0) > 0.8:
            raise DistillQuarantineOrderError(
                f"episode {ep['id']} flagged pre-distill but reached trusted set; "
                "trust predicate and detector are out of sync"
            )

    for ep in trusted:
        summary = summarize_cluster([ep])
        semantic_store.write(summary, partition="trusted", provenance=[ep["id"]])

    # Advisory partition: retrievable only on explicit untrusted-context queries.
    for ep in advisory:
        summary = summarize_cluster([ep])
        semantic_store.write(summary, partition="advisory", provenance=[ep["id"]])

    return len(trusted), len(advisory)


def quarantine(episode_id, episodic_log, semantic_store):
    """Quarantine an episode AND retract any semantic memory derived from it.

    A quarantine that only marks the episode is incomplete: the derived
    summary is the actual damage vector and must be retracted too.
    """
    ep = episodic_log.get(episode_id)
    if ep is None:
        raise DistillQuarantineOrderError(f"unknown episode {episode_id}")

    episodic_log.mark_quarantined(episode_id)

    derived = semantic_store.find_by_provenance(episode_id)
    if derived and not semantic_store.supports_provenance:
        raise DistillQuarantineOrderError(
            f"episode {episode_id} has derived summaries but store lacks "
            "provenance tracking; cannot retract laundered memory"
        )
    for summary in derived:
        semantic_store.retract(summary.id)
