# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-summarizer-synthesized-facts-from-being-re-retrieved-as-primary-evidence-after-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-summarizer-synthesized-facts-from-being-re-retrieved-as-primary-evidence-after-auto-compaction.warrant.json
# Markdown SHA-256:   a4e50aac0537e4d1851d36122fc9442ac30a75c2429fd8a30565276f2e2c3e01
# Code AST SHA-256:   d80cc6dd3ba9b4d5b0dde605e70bba972655f615813ed04f47034e4a8ab09cc3
# Verified Classes:   ProvenanceViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceViolation(RuntimeError):
    """Raised when a compaction-derived claim is treated as primary evidence."""
    pass


def compact_and_evict(summary_claims, retained_turns, evicted_turns, memory_store):
    """
    Enforce: no derived claim may survive as flat fact once its
    primary evidence is evicted. Demote to unverified_inference instead.
    """
    for claim in summary_claims:
        sources = set(claim.get("derived_from", []))
        if not sources:
            # A claim with no source pointer is untraceable; it can never
            # be promoted to evidence.
            claim["provenance"] = "unverified_inference"
            memory_store.upsert(claim)
            continue

        lost = sources & set(evicted_turns)
        if lost:
            # The evidence is gone from context. The claim must not be
            # retrievable as fact.
            claim["provenance"] = "unverified_inference"
            claim["demoted_because"] = sorted(lost)
            memory_store.upsert(claim)
        else:
            # Evidence retained: claim may stay as a cache, still subordinate.
            claim["provenance"] = "cache"
            memory_store.upsert(claim)

    return summary_claims


def retrieve_for_factual_query(query, memory_store, top_k=5):
    """
    Factual retrieval must exclude compaction-derived content unless the
    caller explicitly opts into inference. This is the enforcement point
    the model cannot provide for itself.
    """
    hits = memory_store.search(query, top_k=top_k * 3)
    filtered = [
        h for h in hits
        if h.get("provenance") in ("primary", "cache")
        and h.get("source") != "compaction" or h.get("provenance") == "cache"
    ]
    # Hard rule: any unverified_inference hit that would rank above a
    # primary hit is a provenance violation, not a ranking quirk.
    for h in hits[:top_k]:
        if h.get("provenance") == "unverified_inference":
            has_primary = any(
                f.get("provenance") == "primary" for f in filtered
            )
            if has_primary:
                raise ProvenanceViolation(
                    f"derived claim {h['id']} outranked primary evidence "
                    f"for query {query!r}; demote or re-verify before use"
                )
    return filtered[:top_k]
