# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-a-memory-store-quarantine-a-semantic-promotion-rather-than-resolve-the-conflict-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-a-memory-store-quarantine-a-semantic-promotion-rather-than-resolve-the-conflict-in-place.warrant.json
# Markdown SHA-256:   3a55f0fc94d46f4d9c9508fd165456dc5441bb891e5d117019510a88d1948a2e
# Code AST SHA-256:   0ea1425d6dd20915f3c0cd90ffdd2be3efa04655e0000a12317ab61bdf5e8210
# Verified Classes:   PromotionQuarantineError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PromotionQuarantineError(RuntimeError):
    """Raised when a conflict must be quarantined rather than resolved in place."""
    pass


TRUST_FLOOR = 0.60


def resolve_promotion(conflict_key, winner, loser):
    # winner/loser each carry: value, original_trust, attested_root
    winner_trust = winner["original_trust"]
    loser_trust = loser["original_trust"]

    # Provenance collapsed at promotion -> cannot validate -> quarantine.
    if winner.get("attested_root") is None:
        raise PromotionQuarantineError(
            f"cannot reconstruct provenance for {conflict_key!r}; "
            f"quarantine by default"
        )

    # Winner is untrusted AND the loser was actually more trustworthy
    # before the promotion rewrite laundered the source.
    if winner_trust < TRUST_FLOOR and loser_trust > winner_trust:
        raise PromotionQuarantineError(
            f"conflict on {conflict_key!r}: winner trust {winner_trust:.2f} "
            f"below floor {TRUST_FLOOR:.2f} while loser trust "
            f"{loser_trust:.2f} exceeds it; defer to contested-set"
        )

    # Safe: winner clears the floor on its ORIGINAL provenance.
    return {"key": conflict_key, "value": winner["value"], "resolved": True}


def consolidate(conflicts):
    contested = []
    for key, winner, loser in conflicts:
        try:
            resolve_promotion(key, winner, loser)
        except PromotionQuarantineError as exc:
            contested.append({"key": key, "reason": str(exc)})
    return contested
