# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-trust-score-laundering-across-federated-capability-re-exports-before-routing-commits.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-trust-score-laundering-across-federated-capability-re-exports-before-routing-commits.warrant.json
# Markdown SHA-256:   a2e3dfc16f4185d69438409d94e92ea9d796ae55051a007e7cb1d54e79e1a31d
# Code AST SHA-256:   240e6f57dd02e64e09b0bd15c1e7b6bf814b20252e4235281ebad93e62fade1d
# Verified Classes:   TrustLaunderingError, CapabilityRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TrustLaunderingError(RuntimeError):
    """Raised when a routing decision would inherit a broker's trust for an
    unverified origin agent, or when the warrant chain diverges from the
    executor chain."""


@dataclass(frozen=True)
class CapabilityRecord:
    capability: str
    advertiser_id: str
    origin_id: str
    origin_chain: tuple[str, ...]  # ordered advertiser -> ... -> origin
    origin_trust_signature: Optional[bytes]  # None == unverified re-export


def resolve_admission_trust(
    record: CapabilityRecord,
    trust_map: dict[str, float],
    threshold: float,
) -> float:
    """Compute the effective trust for admitting a task to `record`.

    Invariant: trust attenuates across delegation (min over chain), and an
    unverified or unknown origin fails closed into quarantine.
    """
    if record.origin_id == record.advertiser_id:
        if record.origin_id not in trust_map:
            raise TrustLaunderingError(
                f"first-hand advertiser {record.origin_id} has no trust score; "
                "cannot default to itself"
            )
        effective = trust_map[record.origin_id]
    else:
        if record.origin_trust_signature is None:
            raise TrustLaunderingError(
                f"capability {record.capability!r} re-exported by "
                f"{record.advertiser_id} from {record.origin_id} carries no "
                "origin trust signature; refusing to inherit broker trust"
            )
        if record.origin_id not in record.origin_chain:
            raise TrustLaunderingError(
                f"origin {record.origin_id} absent from provenance chain "
                f"{record.origin_chain}; chain is inconsistent"
            )
        unknown = [a for a in record.origin_chain if a not in trust_map]
        if unknown:
            # Unknown origin is a quarantine state, not a default to advertiser.
            raise TrustLaunderingError(
                f"unresolved trust for chain members {unknown}; "
                "route to quarantine, do not fall back to advertiser score"
            )
        effective = min(trust_map[a] for a in record.origin_chain)

    if effective < threshold:
        raise TrustLaunderingError(
            f"effective trust {effective:.3f} for {record.capability!r} "
            f"(advertiser {record.advertiser_id}, origin {record.origin_id}) "
            f"below admission threshold {threshold:.3f}"
        )
    return effective


def route_task(
    record: CapabilityRecord,
    warrant_issuer_chain: tuple[str, ...],
    executor_id: str,
    trust_map: dict[str, float],
    threshold: float,
) -> str:
    """Admit a task only if trust attenuates cleanly AND the warrant chain
    stays aligned with the executor chain."""
    effective = resolve_admission_trust(record, trust_map, threshold)

    if executor_id != warrant_issuer_chain[-1]:
        raise TrustLaunderingError(
            f"warrant issued by {warrant_issuer_chain[-1]} but executed by "
            f"{executor_id}; issuer/executor divergence indicates a re-minted "
            "warrant that reset the constraint envelope"
        )
    if record.origin_id not in warrant_issuer_chain:
        raise TrustLaunderingError(
            f"warrant chain {warrant_issuer_chain} does not include origin "
            f"{record.origin_id}; warrant was not attenuation-only"
        )
    return f"admitted:{record.capability}:trust={effective:.3f}"
