# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loses-the-provenance-trail-of-a-poisoned-fact-across-a-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loses-the-provenance-trail-of-a-poisoned-fact-across-a-compaction-boundary.warrant.json
# Markdown SHA-256:   76c88481a83901f66ebd7e7f575492950a8699e88ceff83104a43ef7ee5bcce2
# Code AST SHA-256:   0f57c7e1566b58e7ba621112ce730081839fbca674af6b5b5d0bfcc3b1a5e831
# Verified Classes:   ProvenanceDecoherenceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceDecoherenceError(RuntimeError):
    """Raised when a distilled claim crosses a compaction boundary without
    resolvable provenance, or when a conflict cannot be resolved without
    a provenance-blind tie-break."""
    pass


def resolve_conflict(claim_a: dict, claim_b: dict) -> dict:
    """
    claim = {
        "value": ...,
        "trace_id": str | None,
        "trust_class": "verified" | "untrusted" | "unverified" | "derived",
        "confidence": float,
        "write_seq": int,
    }
    Resolve only when provenance is intact on both sides and trust classes
    differ. Otherwise refuse.
    """
    # Boundary guard: any claim lacking a resolvable trace is unverifiable.
    for c in (claim_a, claim_b):
        if c.get("trace_id") is None or c.get("trust_class") is None:
            raise ProvenanceDecoherenceError(
                f"claim {c.get('value')!r} crossed compaction boundary "
                f"without trace_id/trust_class; refusing tie-break"
            )

    ta, tb = claim_a["trust_class"], claim_b["trust_class"]

    # If one side is untrusted/unverified and the other verified, the
    # verified side wins — but only because provenance is present.
    if ta == "verified" and tb != "verified":
        return claim_a
    if tb == "verified" and ta != "verified":
        return claim_b

    # Same trust class, different values: provenance cannot break the tie.
    # A value-based (write_seq / confidence) tie-break here is exactly the
    # silent failure that selects the poisoned first-write.
    if claim_a["value"] != claim_b["value"]:
        raise ProvenanceDecoherenceError(
            f"irreconcilable conflict {claim_a['value']!r} vs "
            f"{claim_b['value']!r} at equal trust_class={ta!r}; "
            f"escalate for independent verification, do not tie-break"
        )
    return claim_a


def compact_and_verify(episodes: list[dict], distilled: list[dict]) -> list[dict]:
    """
    distilled claims must each resolve to a pre-compaction trace segment
    and carry a propagated trust_class. Reject the batch otherwise.
    """
    trace_index = {e["trace_id"]: e for e in episodes if "trace_id" in e}
    out = []
    for claim in distilled:
        tid = claim.get("trace_id")
        if tid is None or tid not in trace_index:
            raise ProvenanceDecoherenceError(
                f"distilled claim {claim.get('value')!r} has no resolvable "
                f"trace segment (trace_id={tid!r}); compaction dropped lineage"
            )
        src_trust = trace_index[tid]["trust_class"]
        # Derivation may only lower trust, never raise it.
        if claim["trust_class"] == "verified" and src_trust != "verified":
            raise ProvenanceDecoherenceError(
                f"claim {claim['value']!r} promoted to verified from "
                f"source trust_class={src_trust!r}; taint not propagated"
            )
        if claim["trust_class"] == "unverified":
            continue  # excluded from downstream preference
        out.append(claim)
    return out
