# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-anomaly-score-as-a-retrieval-time-trust-signal-rather-than-a-write-time-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-anomaly-score-as-a-retrieval-time-trust-signal-rather-than-a-write-time-gate.warrant.json
# Markdown SHA-256:   a0d4ce0da24f193429e13150c40051aec0e60d6a154410e2f554299512f5c19c
# Code AST SHA-256:   a77e3dfec6d62d3abed35033ab96fb338dfd2d0cc298e13c3647b02f59208859
# Verified Classes:   MemoryTrustViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class MemoryTrustViolation(RuntimeError):
    """Raised when a retrieved set violates the read-time trust invariant."""
    pass


def score_retrieval_set(
    query_id: str,
    items: list[dict],
    expected_agreement: float,
    agreement_sigma: float,
    coherence_threshold_sigma: float = 2.5,
) -> list[dict]:
    """
    Apply read-time trust weighting. Each item must carry immutable provenance
    and a write-time anomaly score used only as a weak prior.
    """
    for item in items:
        if not item.get("provenance") or item.get("provenance_mutable", False):
            raise MemoryTrustViolation(
                f"query {query_id}: item {item.get('id')} has missing or mutable "
                f"provenance; trust weight forced to 0.0 and excluded from coherence"
            )

    provenanced = [i for i in items if i.get("provenance") and not i.get("provenance_mutable", False)]
    if len(provenanced) < 2:
        return provenanced

    observed = _pairwise_agreement(provenanced)
    excess = (observed - expected_agreement) / max(agreement_sigma, 1e-9)

    if excess > coherence_threshold_sigma:
        for item in provenanced:
            item["trust_weight"] = item.get("trust_weight", 1.0) * 0.5
            item["flagged_for_review"] = True
        return provenanced

    for item in provenanced:
        prior = item.get("write_anomaly_score", 0.5)
        source_rate = item["provenance"].get("historical_citation_rate", 1.0)
        if source_rate < 0.2:
            item["trust_weight"] = 0.1
        elif prior > 0.995:
            item["trust_weight"] = 0.3
        else:
            item["trust_weight"] = item.get("trust_weight", 1.0)
    return provenanced


def _pairwise_agreement(items: list[dict]) -> float:
    # Placeholder: mean pairwise cosine agreement over item embeddings.
    raise NotImplementedError
