# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-delegation-from-laundering-reputation-across-federated-a2a-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-anchor-delegation-from-laundering-reputation-across-federated-a2a-registries.warrant.json
# Markdown SHA-256:   e0bb8873d83829a667832216abca40d398d45d30713d2d7e09211a7b0ab04222
# Code AST SHA-256:   d7b13ff25b7a9248bc4e7cad193e4bccf15629a4b55cc411c5e3162dad47fade
# Verified Classes:   ReputationLaunderingError, DelegationEdge, AgentCard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReputationLaunderingError(RuntimeError):
    """Raised when a registry attempts to resolve reputation through a
    delegation edge whose scope does not authorize reputation import, or
    when a scalar score is surfaced without provenance/observation count."""


@dataclass
class DelegationEdge:
    issuer: str
    subject: str
    scope: frozenset  # subset of {"identity", "reputation"}
    issued_at: float
    ttl: float


@dataclass
class AgentCard:
    agent_id: str
    registry: str
    anchor_score: float
    leaf_score: float
    observations: int = 0
    edge: Optional[DelegationEdge] = None


K_MIN = 5
THRESHOLD = 0.70


def resolve_reputation(card: AgentCard, now: float) -> dict:
    # Invariant 1: reputation import requires an explicit reputation scope
    # on the delegation edge, and the edge must be live.
    if card.edge is not None:
        if "reputation" not in card.edge.scope:
            raise ReputationLaunderingError(
                f"edge {card.edge.issuer}->{card.edge.subject} lacks "
                f"'reputation' scope; cannot import anchor score"
            )
        if now > card.edge.issued_at + card.edge.ttl:
            raise ReputationLaunderingError(
                f"delegation edge expired at "
                f"{card.edge.issued_at + card.edge.ttl}; reputation import refused"
            )

    # Invariant 2: anchor weight must decay with observed executions.
    # A constant weight is the laundering defect.
    w_anchor = 1.0 / (1.0 + card.observations)
    w_leaf = 1.0 - w_anchor
    score = w_anchor * card.anchor_score + w_leaf * card.leaf_score

    # Invariant 3: below k_min observations the score is a prior, not evidence.
    if card.observations < K_MIN:
        provenance = f"anchor:{card.edge.issuer}" if card.edge else "none"
        return {
            "score": score,
            "confidence": "provisional",
            "observations": card.observations,
            "provenance": provenance,
        }

    return {
        "score": score,
        "confidence": "selection_grade",
        "observations": card.observations,
        "provenance": "local_ledger",
    }


def select_agent(card: AgentCard, now: float) -> bool:
    rep = resolve_reputation(card, now)
    if rep["confidence"] == "provisional" and rep["score"] > THRESHOLD:
        # Provisional high score: allow only sandboxed trial, never
        # direct selection. Caller must honor this signal.
        raise ReputationLaunderingError(
            f"agent {card.agent_id} has provisional score {rep['score']:.3f} "
            f"from {rep['provenance']} with {rep['observations']} observations; "
            f"route to sandbox trial, not direct selection"
        )
    return rep["score"] > THRESHOLD


# Demonstration of the failure being caught:
bad_card = AgentCard(
    agent_id="a-bad",
    registry="reg-B",
    anchor_score=0.94,
    leaf_score=0.0,
    observations=0,
    edge=DelegationEdge(
        issuer="TA-A", subject="a-bad",
        scope=frozenset({"identity"}),  # identity only — no reputation
        issued_at=1000.0, ttl=3600.0,
    ),
)

try:
    select_agent(bad_card, now=1100.0)
except ReputationLaunderingError as e:
    print(f"blocked: {e}")
