# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-delegation-chains-from-silently-widening-scope-across-federation-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-delegation-chains-from-silently-widening-scope-across-federation-boundaries.warrant.json
# Markdown SHA-256:   8620875b7653e5682eae999be76137d59821015ea706d41eb6f6896b0dc9ccab
# Code AST SHA-256:   a12505b8f39e85a16b978b931deb5a3fe0b1d166f6137b276dc050e654464452
# Verified Classes:   ScopeAmplificationError, AgentNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeAmplificationError(RuntimeError):
    """Raised when a delegation chain widens effective scope across a federation edge."""


@dataclass(frozen=True)
class AgentNode:
    org: str
    capabilities: FrozenSet[str]   # advertised on the signed Agent Card
    scope: FrozenSet[str]          # attested by the VC
    revoked: bool = False


def verify_chain(chain: list[AgentNode]) -> FrozenSet[str]:
    """
    Verify a federated delegation chain and return the admitted effective scope.

    Enforces the non-widening invariant:
      - card capabilities must be a subset of the node's VC scope
      - each child's VC scope must be a subset of its parent's VC scope
      - no ancestor may be revoked (transitive freshness)
      - effective scope is the INTERSECTION across the chain, never the union
    """
    if not chain:
        raise ScopeAmplificationError("empty delegation chain")

    effective = chain[0].scope
    for i, node in enumerate(chain):
        # 1. Presentation must not exceed attestation.
        over_advertised = node.capabilities - node.scope
        if over_advertised:
            raise ScopeAmplificationError(
                f"node {i} ({node.org}) advertises {sorted(over_advertised)} "
                f"not present in its attested VC scope"
            )

        # 2. Transitive freshness: any revoked link invalidates the chain.
        if node.revoked:
            raise ScopeAmplificationError(
                f"node {i} ({node.org}) is revoked; chain invalid transitively"
            )

        # 3. Delegation must narrow, never widen.
        if i > 0:
            widened = node.scope - chain[i - 1].scope
            if widened:
                raise ScopeAmplificationError(
                    f"edge {i-1}->{i} widens scope by {sorted(widened)}"
                )

        # 4. Effective scope is the intersection.
        effective = effective & node.scope

    return effective


if __name__ == "__main__":
    # The observed incident: card unions org defaults, VC correctly narrowed.
    orchestrator = AgentNode(
        "org-A",
        capabilities=frozenset({"read:invoices", "write:payments"}),
        scope=frozenset({"read:invoices", "write:payments"}),
    )
    specialist = AgentNode(
        "org-B",
        capabilities=frozenset({"read:invoices", "read:contracts"}),  # card over-advertises
        scope=frozenset({"read:invoices"}),                          # VC correctly narrowed
    )
    executor = AgentNode(
        "org-C",
        capabilities=frozenset({"read:invoices", "read:contracts"}),
        scope=frozenset({"read:invoices", "read:contracts"}),
    )

    # Fails at node 1: specialist's card advertises read:contracts not in its VC.
    verify_chain([orchestrator, specialist, executor])
