# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-semantic-store-promotion-when-episodic-evidence-is-mutually-contradictory-across-writers.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-semantic-store-promotion-when-episodic-evidence-is-mutually-contradictory-across-writers.warrant.json
# Markdown SHA-256:   da2987ed58e62fc3621380b94d66f35589622be96f2724c1fdeed1387af33b90
# Code AST SHA-256:   5539f194df698daf6afdd1db7e4ce3f45f39dee3a4eeb5041774df1e42d57447
# Verified Classes:   PromotionArbitrationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PromotionArbitrationError(RuntimeError):
    """Raised when an episodic→semantic promotion violates the ancestry/contradiction invariant."""
    pass


def promote_to_semantic(episodic_records, semantic_store, confidence_floor=0.8):
    # Step 1: collapse to observation roots by ancestry.
    roots = {}
    for rec in episodic_records:
        root_id = rec.get("ancestor", rec["id"])
        # keep the original (earliest) record for each root
        if root_id not in roots or rec["t"] < roots[root_id]["t"]:
            roots[root_id] = rec

    root_set = list(roots.values())

    # Step 2: require at least one direct-observation root.
    direct_roots = [r for r in root_set if r.get("source") == "direct"]
    if not direct_roots:
        raise PromotionArbitrationError(
            f"no direct-observation root in {len(root_set)} root(s); "
            f"all records are peer-derived (laundering chain) — rejecting promotion"
        )

    # Step 3: contradiction detection across roots.
    by_key = {}
    for r in root_set:
        by_key.setdefault((r["subject"], r["predicate"]), set()).add(r["object"])
    for key, objects in by_key.items():
        if len(objects) > 1:
            raise PromotionArbitrationError(
                f"contradictory roots for {key}: {sorted(objects)} — "
                f"escalate to re-observation, do not arbitrate by recency"
            )

    # Step 4: confidence floor on the strongest direct root.
    best = max(direct_roots, key=lambda r: r["confidence"])
    if best["confidence"] < confidence_floor:
        raise PromotionArbitrationError(
            f"best direct root confidence {best['confidence']} below floor {confidence_floor}"
        )

    semantic_store[best["id"]] = {
        "subject": best["subject"],
        "predicate": best["predicate"],
        "object": best["object"],
        "confidence": best["confidence"],
        "provenance_roots": list(roots.keys()),
    }
    return semantic_store[best["id"]]
