# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-authorization-scope-reconciliation-failure-in-cross-org-agent-federation-policy-engines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-authorization-scope-reconciliation-failure-in-cross-org-agent-federation-policy-engines.warrant.json
# Markdown SHA-256:   e5396e7b2eb8c1ce080a1c3280318a83c5cce30f9c7289abd438a516e1d8b984
# Code AST SHA-256:   6f674c842af7c123d39a85d914dbaa069507d2149dcb6cfd4e4a52d60086802d
# Verified Classes:   ScopeReconciliationError, ResolvedScope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ScopeReconciliationError(RuntimeError):
    """Raised when cross-org scope denotations cannot be safely intersected."""
    pass


@dataclass(frozen=True)
class ResolvedScope:
    token: str
    namespace_hash: str          # hash of the resource namespace the engine resolved against
    cardinality: int             # number of resources the token denotes locally
    signed_modifiers: frozenset  # modifiers covered by the warrant signature
    unsigned_modifiers: frozenset = field(default_factory=frozenset)


def _descriptor_fingerprint(rs: ResolvedScope) -> str:
    payload = f"{rs.token}|{rs.namespace_hash}|{rs.cardinality}|{sorted(rs.signed_modifiers)}"
    return hashlib.sha256(payload.encode()).hexdigest()


def reconcile_pre_execution(
    token: str,
    local: ResolvedScope,
    remote: ResolvedScope,
) -> ResolvedScope:
    """
    Sound boundary: intersect denotations BEFORE the agent's first tool call.
    Fails closed on unsigned modifiers and on denotational disagreement.
    """
    if local.token != remote.token:
        raise ScopeReconciliationError(
            f"token mismatch: {local.token!r} vs {remote.token!r}"
        )

    # Unsigned modifiers are advisory; they cannot be trusted to narrow denotation.
    if local.unsigned_modifiers or remote.unsigned_modifiers:
        raise ScopeReconciliationError(
            f"scope {token!r} carries unsigned modifiers "
            f"{local.unsigned_modifiers | remote.unsigned_modifiers}; "
            f"denotation cannot be verified — attenuating to empty set"
        )

    if local.namespace_hash != remote.namespace_hash:
        raise ScopeReconciliationError(
            f"namespace divergence for {token!r}: "
            f"{local.namespace_hash[:12]} vs {remote.namespace_hash[:12]}"
        )

    # Cardinality agreement is the structural signal of denotational intersection.
    if local.cardinality != remote.cardinality:
        expansion = max(local.cardinality, remote.cardinality) / max(
            min(local.cardinality, remote.cardinality), 1
        )
        raise ScopeReconciliationError(
            f"denotational mismatch for {token!r}: "
            f"{local.cardinality} vs {remote.cardinality} "
            f"({expansion:.1f}x expansion) — refusing federated execution"
        )

    if _descriptor_fingerprint(local) != _descriptor_fingerprint(remote):
        raise ScopeReconciliationError(
            f"descriptor fingerprint divergence for {token!r}"
        )

    # Safe: intersection equals both denotations.
    return ResolvedScope(
        token=token,
        namespace_hash=local.namespace_hash,
        cardinality=local.cardinality,
        signed_modifiers=local.signed_modifiers & remote.signed_modifiers,
    )
