# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-in-its-own-long-horizon-memory-when-the-poisoning-vector-is-a-legitimate-looking-consolidation-of-a-true-fa.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-in-its-own-long-horizon-memory-when-the-poisoning-vector-is-a-legitimate-looking-consolidation-of-a-true-fa.warrant.json
# Markdown SHA-256:   c2b2875210d3e1197d7e919e1e2069312685781959ad1d1b3fd3703a360b683a
# Code AST SHA-256:   9411a53fb5205b97b74bcb5d93e32262fc4c7d0df7cd01934519159a0d715c15
# Verified Classes:   EnvelopeErosionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EnvelopeErosionError(RuntimeError):
    """Raised when a semantic promotion strips qualifiers that made the source episode true."""
    pass


QUALIFIER_KEYS = ("deploy", "version", "ts", "caller", "env", "region")


def extract_envelope(episode: dict) -> dict:
    """Pull validity predicates out of an episodic record's metadata."""
    meta = episode.get("metadata", {})
    return {k: meta[k] for k in QUALIFIER_KEYS if k in meta}


def promote_to_semantic(episode: dict, distilled_claim: dict) -> dict:
    """
    Gate semantic promotion on envelope preservation, not just content entailment.
    distilled_claim is expected to carry its own 'envelope' dict produced by the consolidator.
    """
    source_envelope = extract_envelope(episode)
    claim_envelope = distilled_claim.get("envelope", {})

    # If the source episode carried qualifiers, the distilled claim MUST preserve them.
    if source_envelope:
        missing = set(source_envelope) - set(claim_envelope)
        if missing:
            raise EnvelopeErosionError(
                f"Consolidation of episode {episode.get('id')!r} dropped qualifiers "
                f"{sorted(missing)}; claim {distilled_claim.get('id')!r} is unenveloped "
                f"and must remain episodic."
            )
        # Preserved keys must also preserve values (no silent widening).
        for k, v in source_envelope.items():
            if claim_envelope[k] != v:
                raise EnvelopeErosionError(
                    f"Envelope value drift on {k!r}: source={v!r} claim={claim_envelope[k]!r}"
                )

    distilled_claim["envelope"] = claim_envelope
    distilled_claim["source_episode"] = episode.get("id")
    return distilled_claim


def retrieve_for_action(store, subject: str, predicate: str, context: dict):
    """
    Return only entries whose envelope evaluates true against current context.
    Unverifiable envelopes are treated as unverified, not true.
    """
    for entry in store.lookup(subject, predicate):
        env = entry.get("envelope", {})
        if not env:
            # Unenveloped entry: cannot be attested as currently valid.
            continue
        if any(context.get(k) != v for k, v in env.items()):
            continue
        return entry
    raise EnvelopeErosionError(
        f"No envelope-valid memory for {subject}.{predicate} under context {context!r}; "
        f"fall back to episodic lookup."
    )
