# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-reputation-laundering-during-cross-org-agent-federation-trust-bootstrapping.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-reputation-laundering-during-cross-org-agent-federation-trust-bootstrapping.warrant.json
# Markdown SHA-256:   4ff29b71a14875d881c38df3f017f855fb4b26668ced28749c314c5e13ad20ef
# Code AST SHA-256:   4256bc546917f2763c8791fc387ea8e67197924eae92093182d3d16627b787a6
# Verified Classes:   ReputationLaunderingError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class ReputationLaunderingError(RuntimeError):
    """Raised when an attestation edge would close a trust-derivation cycle."""
    pass


@dataclass
class Attestation:
    attester_id: str
    subject_id: str
    score: float
    epoch: int
    ancestry_digest: str  # rolling hash of attester's derivation sources
    signature: bytes = b""


def _digest(ids: Set[str]) -> str:
    h = hashlib.sha256()
    for i in sorted(ids):
        h.update(i.encode())
        h.update(b"\x00")
    return h.hexdigest()


def admit_attestation(
    att: Attestation,
    subject_known_ancestry: Set[str],
    epoch_floor: int,
) -> None:
    """
    Per-edge admission test. Rejects if the edge closes a derivation cycle
    or violates epoch monotonicity. Raises ReputationLaunderingError.
    """
    if att.epoch < epoch_floor:
        raise ReputationLaunderingError(
            f"stale edge: attester={att.attester_id} epoch={att.epoch} "
            f"< floor={epoch_floor}"
        )
    # Cycle test: subject must not appear in attester's derivation ancestry.
    # We reconstruct the attester's claimed ancestry set and check membership.
    # In production the digest is compared against a signed ancestry set;
    # here we treat subject_known_ancestry as the attester's disclosed sources.
    if att.subject_id in subject_known_ancestry:
        raise ReputationLaunderingError(
            f"cycle detected: subject={att.subject_id} appears in "
            f"attester={att.attester_id} ancestry_digest={att.ancestry_digest}"
        )
    # Digest integrity: disclosed ancestry must match the claimed digest.
    if _digest(subject_known_ancestry) != att.ancestry_digest:
        raise ReputationLaunderingError(
            f"ancestry digest mismatch for attester={att.attester_id}: "
            f"disclosed set does not match signed digest"
        )


def bootstrap_scores(
    attestations: list[Attestation],
    seeds: Dict[str, float],
    intra_org: Dict[str, str],  # agent_id -> org_id
) -> Dict[str, float]:
    """
    Fixed ordering: inter-org edges resolved before intra-org edges,
    so bootstrap seeds cannot re-enter through same-org ancestry.
    """
    scores = dict(seeds)
    # Partition edges by whether attester and subject share an org.
    inter, intra = [], []
    for att in attestations:
        if intra_org.get(att.attester_id) != intra_org.get(att.subject_id):
            inter.append(att)
        else:
            intra.append(att)

    for att in inter + intra:  # inter first — the invariant
        ancestry = {att.attester_id}  # attester's own lineage root
        admit_attestation(att, ancestry, epoch_floor=0)
        # Monotone but cycle-safe aggregation: contribution bounded by attester seed.
        contrib = 0.5 * scores.get(att.attester_id, 0.0) * att.score
        scores[att.subject_id] = scores.get(att.subject_id, 0.0) + contrib

    return scores
