# 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-corroboration-is-itself-poisoned-trust-weighted-retrieval-and-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-semantic-store-promotion-when-episodic-corroboration-is-itself-poisoned-trust-weighted-retrieval-and-t.warrant.json
# Markdown SHA-256:   7f9e7d1d0051788847a2ee28dd2e7efa8f23b0f47eca968e307f6015cb4742ca
# Code AST SHA-256:   48564dd486b03e08838b819a7daf0dff92f3b1d7e7012181371a55f67ed42dd4
# Verified Classes:   CircularSupportError, InsufficientRootIndependence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CircularSupportError(RuntimeError):
    """Raised when a semantic-store promotion's supporting episodes share a
    provenance root with the candidate fact itself, or were generated by
    actions the candidate authorized. Circular support is zero evidence."""


class InsufficientRootIndependence(RuntimeError):
    """Raised when provenance-collapsed support is below threshold K even
    though raw episode count meets it. Candidate must be quarantined, not
    promoted at reduced trust."""


def promote_candidate(
    candidate_fact_id: str,
    supporting_episodes: list[dict],
    k_threshold: int,
    ancestors: set[str],
) -> dict:
    # Each episode: {"record_id", "provenance_root", "trust",
    #                "caused_by_facts": set[str]}
    if not supporting_episodes:
        raise InsufficientRootIndependence(
            f"no supporting episodes for {candidate_fact_id}"
        )

    # Hard boundary: circular support is zero evidence, not weak evidence.
    for ep in supporting_episodes:
        causal = ep.get("caused_by_facts", set())
        if candidate_fact_id in causal or (causal & ancestors):
            raise CircularSupportError(
                f"episode {ep['record_id']} was caused by candidate "
                f"{candidate_fact_id} or its ancestors {causal & ancestors}; "
                f"refusing promotion"
            )

    # Collapse by provenance root BEFORE counting. Views are not evidence.
    by_root: dict[str, list[dict]] = {}
    for ep in supporting_episodes:
        by_root.setdefault(ep["provenance_root"], []).append(ep)

    root_count = len(by_root)
    if root_count < k_threshold:
        raise InsufficientRootIndependence(
            f"{candidate_fact_id}: {len(supporting_episodes)} episodes "
            f"collapse to {root_count} provenance roots, need {k_threshold}"
        )

    # Compose trust across independent roots only; max within a root.
    root_trusts = [max(e["trust"] for e in eps) for eps in by_root.values()]
    composed = 1.0
    for t in root_trusts:
        composed *= (1.0 - t)
    composed = 1.0 - composed

    return {
        "fact_id": candidate_fact_id,
        "supporting_roots": sorted(by_root.keys()),
        "composed_trust": composed,
        # Authorization gates on the weakest root, not the composition.
        "min_root_trust": min(root_trusts),
        "advisory_only": len(root_trusts) < k_threshold + 1,
    }
