# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-low-confidence-provenance-poisoning-when-trust-scores-are-aggregated-across-heterogeneous-write-paths-in-a-persistent-ag.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-low-confidence-provenance-poisoning-when-trust-scores-are-aggregated-across-heterogeneous-write-paths-in-a-persistent-ag.warrant.json
# Markdown SHA-256:   ac5246a12eda6a1aead53f7c8c9e70c07b97816a22500fb794166deb096adc35
# Code AST SHA-256:   c78c92dff046742ab4dab124b5c9f71d3a54170c156bde08cadec3612992ecbf
# Verified Classes:   ProvenanceLaunderingError, Contribution
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a trust promotion would rely on a contribution that was
    produced after the record entered an agent context (dependent corroboration)."""
    pass


class Contribution:
    __slots__ = ("trust", "write_seq", "path", "agrees")

    def __init__(self, trust: float, write_seq: int, path: str, agrees: bool):
        self.trust = trust
        self.write_seq = write_seq
        self.path = path
        self.agrees = agrees


def promote_record(
    record_id: str,
    contributions: list[Contribution],
    first_read_seq: int | None,
    promotion_threshold: float = 0.55,
) -> float:
    if not contributions:
        raise ProvenanceLaunderingError(f"{record_id}: no contributions to aggregate")

    original = min(contributions, key=lambda c: c.write_seq)
    original_trust = original.trust

    independent = [
        c for c in contributions
        if first_read_seq is None or c.write_seq < first_read_seq
    ]
    dependent = [
        c for c in contributions
        if first_read_seq is not None and c.write_seq >= first_read_seq
    ]

    if not independent:
        raise ProvenanceLaunderingError(
            f"{record_id}: every contribution postdates first read at seq {first_read_seq}"
        )

    # Agreeing dependent contributions cannot raise the ceiling.
    laundering = [
        c for c in dependent
        if c.agrees and c.trust > original_trust
    ]
    if laundering:
        raise ProvenanceLaunderingError(
            f"{record_id}: {len(laundering)} dependent agreeing contribution(s) "
            f"exceed original trust {original_trust:.2f}; "
            f"paths={[c.path for c in laundering]}"
        )

    effective = max(c.trust for c in independent)
    if effective < promotion_threshold:
        return effective  # not promoted; caller keeps record in review

    # Corrections (disagreeing dependent contributions) legitimately lower trust.
    for c in dependent:
        if not c.agrees:
            effective = min(effective, c.trust)

    return effective
