# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-a2a-capability-scope-escalation-when-federated-policy-engines-disagree-on-scope-closure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-a2a-capability-scope-escalation-when-federated-policy-engines-disagree-on-scope-closure.warrant.json
# Markdown SHA-256:   c16112e322f8284a7c872d810c754f5bd3cbd47144fcc005ada8fb4544c01d6f
# Code AST SHA-256:   b10a2176fbab2a2f3e330228e17be74f27970fd1ebb37c6acbf3aea0c72ba6cd
# Verified Classes:   ScopeClosureMismatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeClosureMismatch(RuntimeError):
    """Raised when a federated warrant's capability cannot be traced to a positive local policy decision."""
    pass


def reconcile_and_mint_warrant(
    requested_scopes: set[str],
    advertised_card: set[str],
    policy_engine,
    principal_org: str,
    local_org: str,
) -> dict:
    # Derivational intersection: unsound when the card is not a projection of the policy.
    candidate = requested_scopes & advertised_card
    if not candidate:
        raise ScopeClosureMismatch(
            f"empty intersection for principal {principal_org} -> {local_org}"
        )

    # Guardrail: every candidate capability must have a positive local decision.
    warrant_scopes = set()
    for scope in candidate:
        decision = policy_engine.decide(
            principal_org=principal_org,
            action=scope,
            resource_org=local_org,
        )
        if decision.effect != "permit":
            # Implicit deny surfaced as absence of positive decision -> refuse to mint.
            raise ScopeClosureMismatch(
                f"scope {scope!r} in intersection has no positive local decision "
                f"(effect={decision.effect!r}); card is not a projection of policy"
            )
        warrant_scopes.add(scope)

    return {
        "scopes": sorted(warrant_scopes),
        "provenance": "consultative",
        "issuer_org": local_org,
        "principal_org": principal_org,
    }
