# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-promotes-a-poisoned-episodic-memory-across-a-trust-tier-boundary-and-the-verifier-replays-the-wrong-provenance-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-promotes-a-poisoned-episodic-memory-across-a-trust-tier-boundary-and-the-verifier-replays-the-wrong-provenance-chain.warrant.json
# Markdown SHA-256:   874754e3b4b65f0d684fd2596727bcaf5a0253f1e50384eeee65cdd670d3c8bd
# Code AST SHA-256:   ebd7e8df448eb5a435569688bf50f0ba938bd016fdda524eec1b448b92fc7b3e
# Verified Classes:   TrustTier, Source, Atom, PromotionCandidate, ProvenanceSubstitutionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable

class TrustTier(IntEnum):
    UNTRUSTED = 0
    EPISODIC = 1
    TASK = 2
    SEMANTIC = 3

@dataclass(frozen=True)
class Source:
    id: str
    tier: TrustTier
    text: str

@dataclass(frozen=True)
class Atom:
    field: str
    value: str

@dataclass
class PromotionCandidate:
    claim_id: str
    atoms: list[Atom]
    provenance: list[str]  # source ids cited by the promoter

class ProvenanceSubstitutionError(RuntimeError):
    """Raised when a promotion atom is warranted only by a source below the target tier."""

def _entails(source: Source, atom: Atom) -> bool:
    # In production: structured extraction over raw source bytes, not the distilled claim.
    return atom.value in source.text

def verify_promotion(
    candidate: PromotionCandidate,
    sources: dict[str, Source],
    target_tier: TrustTier,
) -> None:
    # Guard 1: every cited source must exist (no dangling provenance).
    missing = [sid for sid in candidate.provenance if sid not in sources]
    if missing:
        raise ProvenanceSubstitutionError(
            f"claim {candidate.claim_id}: cited sources not found: {missing}"
        )

    cited = [sources[sid] for sid in candidate.provenance]

    # Guard 2: conjunction invariant — each ATOM must be entailed by a source
    # at or above the target tier. Per-source support is insufficient.
    for atom in candidate.atoms:
        warranting = [s for s in cited if s.tier >= target_tier and _entails(s, atom)]
        if not warranting:
            untrusted_only = [s.id for s in cited if _entails(s, atom)]
            raise ProvenanceSubstitutionError(
                f"claim {candidate.claim_id}: atom {atom.field}={atom.value!r} "
                f"warranted only by sub-tier sources {untrusted_only}; "
                f"target_tier={target_tier.name}"
            )

    # Guard 3: claim text must not contain atoms absent from all cited sources
    # (catches distillation embellishment like an invented 'verified').
    # Caller is responsible for atomizing the stored claim before this call.

# Example: the T-2201 -> S-0091 trace above.
sources = {
    "E-4417": Source("E-4417", TrustTier.EPISODIC,
                     "Billing token rotated to tok-X (verified)."),
    "E-4418": Source("E-4418", TrustTier.EPISODIC,
                     "Billing token rotated; see secrets manager."),
}
# Note: E-4417 is EPISODIC-tier; the injected 'tok-X' is below SEMANTIC.
candidate = PromotionCandidate(
    claim_id="T-2201",
    atoms=[Atom("token", "tok-X"), Atom("rotation", "confirmed")],
    provenance=["E-4417", "E-4418"],
)
verify_promotion(candidate, sources, TrustTier.SEMANTIC)
# -> ProvenanceSubstitutionError: atom token='tok-X' warranted only by sub-tier
#    sources ['E-4417']; target_tier=SEMANTIC
