# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-credential-whose-scope-was-narrowed-by-an-intermediate-issuer-it-never-directly-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-credential-whose-scope-was-narrowed-by-an-intermediate-issuer-it-never-directly-trusted.warrant.json
# Markdown SHA-256:   c011a623d6a81c454d31bdfc1e9a2f26d8d0f68050ba0b9467a23150c7a60a15
# Code AST SHA-256:   b32b1855b9667382f8b7c364c827e800e1442fb76635c7255182805dfe9c2ba2
# Verified Classes:   UnresolvableScopeError, ScopeTerm, DelegatedCredential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnresolvableScopeError(RuntimeError):
    """Raised when a delegated scope term's denotation cannot be established."""
    pass


@dataclass
class ScopeTerm:
    term: str
    introduced_by: str
    policy_version: Optional[str] = None
    resource_set: Optional[frozenset] = None  # explicit denotation, if pinned


@dataclass
class DelegatedCredential:
    issuer: str
    scopes: list = field(default_factory=list)


# Resolvers keyed by (issuer, policy_version). Absence means "cannot resolve".
POLICY_RESOLVERS = {
    ("idp.corp", "v7"): lambda term: frozenset(f"repo-{i}" for i in range(1, 13)),
    ("broker-eu", "v2"): lambda term: frozenset(f"repo-{i}" for i in range(1, 5000)),
}


def resolve_denotation(scope: ScopeTerm) -> frozenset:
    if scope.resource_set is not None:
        return scope.resource_set
    if scope.policy_version is None:
        raise UnresolvableScopeError(
            f"scope {scope.term!r} from {scope.introduced_by!r} has no policy_version "
            f"and no explicit resource_set; denotation is undefined"
        )
    resolver = POLICY_RESOLVERS.get((scope.introduced_by, scope.policy_version))
    if resolver is None:
        raise UnresolvableScopeError(
            f"no resolver for issuer {scope.introduced_by!r} policy "
            f"{scope.policy_version!r}; cannot compute denotation of {scope.term!r}"
        )
    return resolver(scope.term)


def verify_chain_monotone(chain: list) -> frozenset:
    """Return effective resource set; raise if any hop widens or is unresolvable."""
    effective = None
    for hop_index, cred in enumerate(chain):
        hop_set = frozenset()
        for scope in cred.scopes:
            hop_set |= resolve_denotation(scope)
        if effective is not None and not hop_set <= effective:
            raise UnresolvableScopeError(
                f"hop {hop_index} ({cred.issuer!r}) widens scope: "
                f"{sorted(hop_set - effective)} not in prior hop"
            )
        effective = hop_set
    return effective


# The observed failure, reproduced: hop 2 dropped resource_set, hop 3 kept bare term.
chain = [
    DelegatedCredential("idp.corp", [
        ScopeTerm("repo:write", "idp.corp", "v7",
                  frozenset(f"repo-{i}" for i in range(1, 13))),
    ]),
    DelegatedCredential("orch-1", [
        ScopeTerm("repo:write", "orch-1", None, None),  # resource_set dropped
    ]),
    DelegatedCredential("broker-eu", [
        ScopeTerm("repo:write", "broker-eu", "v2", None),  # bare term, own policy
    ]),
]

if __name__ == "__main__":
    try:
        effective = verify_chain_monotone(chain)
        print("authorized for:", sorted(effective))
    except UnresolvableScopeError as e:
        # Correct behavior: fail closed. The bare term at hop 2 cannot be
        # resolved under orch-1's (absent) policy, so the chain is rejected
        # rather than silently widened to broker-eu's 4999-repo namespace.
        print("REJECTED:", e)
        raise
