# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-brokered-capability-grant-when-transitive-trust-paths-disagree-across-federated-administrative-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-brokered-capability-grant-when-transitive-trust-paths-disagree-across-federated-administrative-domains.warrant.json
# Markdown SHA-256:   a34c3e78cc4547ba0d652abfb599d34c8bcd66091adc8f6bc79e08b7f219746e
# Code AST SHA-256:   838a00ebf9d93e8e63b8eb973444bebeef1bd2182f762ba3dabecd508b9c6d65
# Verified Classes:   FederationScopeDivergence, PathWitness
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class FederationScopeDivergence(RuntimeError):
    """Raised when live trust paths disagree on the effective capability scope."""


@dataclass(frozen=True)
class PathWitness:
    broker_id: str
    origin_scope: FrozenSet[str]
    hop_scope: FrozenSet[str]
    narrowing_proven: bool


def admit_grant(
    grant_id: str,
    paths: list[PathWitness],
    exercised_scope: FrozenSet[str],
    allow_narrowest_wins: bool = False,
) -> FrozenSet[str]:
    if not paths:
        raise FederationScopeDivergence(
            f"grant {grant_id}: no live trust paths; refusing admission"
        )

    # Any unproven hop contributes the empty set, collapsing the meet.
    verified = [p for p in paths if p.narrowing_proven]
    if len(verified) != len(paths):
        unproven = [p.broker_id for p in paths if not p.narrowing_proven]
        raise FederationScopeDivergence(
            f"grant {grant_id}: unproven narrowing at brokers {unproven}; "
            f"meet collapses to empty by policy"
        )

    # Origin-scope fields must agree across all paths for the same grant-id.
    origin_scopes = {p.origin_scope for p in verified}
    if len(origin_scopes) > 1:
        raise FederationScopeDivergence(
            f"grant {grant_id}: origin-scope disagreement across paths "
            f"{[p.broker_id for p in verified]}; possible forged or split-brain broker"
        )

    meet = verified[0].hop_scope
    for p in verified[1:]:
        meet = meet & p.hop_scope

    if not meet:
        raise FederationScopeDivergence(
            f"grant {grant_id}: meet of path scopes is empty; refusing"
        )

    if not exercised_scope <= meet:
        if allow_narrowest_wins:
            narrowest = min((p.hop_scope for p in verified), key=len)
            if exercised_scope <= narrowest:
                return narrowest
        raise FederationScopeDivergence(
            f"grant {grant_id}: exercised scope {sorted(exercised_scope)} "
            f"exceeds meet {sorted(meet)}"
        )

    return meet
