# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-has-presented-a-valid-aaif-warrant-under-a-foreign-trust-root-and-where-the-cross-root-proof-chain-silen.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-has-presented-a-valid-aaif-warrant-under-a-foreign-trust-root-and-where-the-cross-root-proof-chain-silen.warrant.json
# Markdown SHA-256:   17657e727941224ce6a2c9e44e98e2b75cdcd6cf573d51bd4013bc486a643536
# Code AST SHA-256:   8c6ffe7b3cc4346c821ba21fdb0c60b0d69d4b1a32bbc147e641651816de985a
# Verified Classes:   ForeignRootUnbound, UnmappedCapability, ScopeContainmentViolation, Policy, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForeignRootUnbound(RuntimeError):
    """Raised when a presented warrant's chain terminates at a key not named
    in the verifier's signed policy root set. Structural, not policy-advisory."""


class UnmappedCapability(RuntimeError):
    """Raised when a warrant's capability string is absent from the verifier's
    closed capability map. Unknown capabilities fail closed."""


class ScopeContainmentViolation(RuntimeError):
    """Raised when the mapped scope is not a subset of the cross-root
    endorsement's scope."""


@dataclass
class Policy:
    trusted_roots: frozenset[str]           # terminal keys the verifier honors
    capability_map: dict[str, str]          # foreign cap -> local scope
    endorsements: dict[str, frozenset[str]] # root_key -> endorsed scopes


@dataclass
class Warrant:
    chain: list[str]                        # x5c leaf..intermediate (root may be omitted)
    capability: str
    subject: str


def walk_to_policy_root(chain: list[str], policy: Policy) -> str:
    # The walker's ONLY valid terminals are policy-named roots. No TOFU,
    # no discovery-seeded cache, no first-seen-intermediate promotion.
    for key in reversed(chain):
        if key in policy.trusted_roots:
            return key
    raise ForeignRootUnbound(
        f"chain terminals {chain[-1]!r} not in policy.trusted_roots; "
        f"refusing TOFU fallback"
    )


def authorize(w: Warrant, policy: Policy) -> str:
    root = walk_to_policy_root(w.chain, policy)          # step 1-2
    if w.capability not in policy.capability_map:        # step 3
        raise UnmappedCapability(
            f"capability {w.capability!r} absent from closed map; fail closed"
        )
    mapped = policy.capability_map[w.capability]
    endorsed = policy.endorsements.get(root, frozenset())
    if mapped not in endorsed:                           # step 4
        raise ScopeContainmentViolation(
            f"mapped scope {mapped!r} not endorsed by root {root!r}"
        )
    return f"authorized:{w.subject}:{mapped}:root={root}"


# Reproduction of the observed failure:
policy = Policy(
    trusted_roots=frozenset({"A2A-Root"}),               # verifier's real root
    capability_map={},                                   # no AAIF caps mapped
    endorsements={"A2A-Root": frozenset({"a2a:resource:read"})},
)
warrant = Warrant(
    chain=["Agent-Orch-cert", "AAIF-OrgCA-cert"],        # root omitted
    capability="aaif.cap.files.write:v2",
    subject="agent-orch",
)

try:
    authorize(warrant, policy)
except ForeignRootUnbound as e:
    # Under the invariant this fires FIRST — before signature verify,
    # before scope mapping. The observed system instead promoted
    # AAIF-OrgCA to a root via TOFU and returned authorized:true.
    print(f"REJECTED (structural): {e}")
