# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-emergent-collusion-in-federated-agent-populations-the-shared-scratchpad-correlation-leak.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-emergent-collusion-in-federated-agent-populations-the-shared-scratchpad-correlation-leak.warrant.json
# Markdown SHA-256:   4a7b8ec27936064a2f149a2940e66d1fc279b52f8ecd906df1472f1d9a9e1def
# Code AST SHA-256:   0196be6f99fc09220b0b1aa099ddc13b8471346d30e0d76c2da17f2b1a608987
# Verified Classes:   ConfoundedCollusionVerdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ConfoundedCollusionVerdict(RuntimeError):
    """Raised when a collusion verdict cannot be separated from shared-state exposure."""
    pass


def evaluate_cluster(cluster, scratchpad, reassignment_result=None):
    """
    cluster: list of agent records, each with .reads (set of record ids),
             .first_correlated_seq (int), .actions (list)
    scratchpad: maps record_id -> {'seq': int, 'writers': set, 'readers': set}
    reassignment_result: None if untested, else dict agent_id -> bool (still correlated)
    """
    # Provenance precondition: fail closed if any member lacks read provenance.
    for member in cluster:
        if member.reads is None or member.first_correlated_seq is None:
            raise ConfoundedCollusionVerdict(
                f"agent {member.id} missing read provenance; cannot rule out common cause"
            )

    # Test A: is there a shared upstream record read by all, written before all outputs?
    common_reads = set.intersection(*(m.reads for m in cluster))
    confounded = False
    for rec_id in common_reads:
        rec = scratchpad.get(rec_id)
        if rec is None:
            raise ConfoundedCollusionVerdict(
                f"record {rec_id} in read set but absent from store; ordering undecidable"
            )
        if all(m.first_correlated_seq > rec['seq'] for m in cluster):
            confounded = True
            break

    # Test B: persistence across shard reassignment.
    if reassignment_result is None:
        if confounded:
            return "Indeterminate"  # do NOT quarantine on a confounded signal
        return "Collusion"  # Test A negative and no persistence data: still suspect
    persists = all(reassignment_result.get(m.id, False) for m in cluster)

    if persists:
        return "Collusion"          # coordination survives isolation -> real
    if confounded:
        return "SharedStateExposure"  # correlation dissolves -> common cause
    # Correlation vanished but no shared cause found: provenance gap, not innocence.
    raise ConfoundedCollusionVerdict(
        "correlation dissolved on reassignment without identifiable common cause; "
        "audit trail incomplete"
    )
