# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-identity-warrant-has-silently-decoupled-from-its-tool-calling-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-aaif-identity-warrant-has-silently-decoupled-from-its-tool-calling-scope.warrant.json
# Markdown SHA-256:   84ff5537279369ee738b58f999386e17e0c20b54983663e820486c406a173178
# Code AST SHA-256:   50dce49401989b92b8b33621ad00edad25202340d48e451d4bf312d4b21076e1
# Verified Classes:   ScopeDecouplingError, EnforcementObservation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ScopeDecouplingError(RuntimeError):
    """Raised when tool-shim and bus-envelope enforcement disagree on
    allow/deny or on the warrant generation they evaluated against."""
    pass


@dataclass(frozen=True)
class EnforcementObservation:
    allowed: bool
    warrant_generation: int
    source: str  # "shim" | "bus"


def reconcile_enforcement(
    action: str,
    shim: Optional[EnforcementObservation],
    bus: Optional[EnforcementObservation],
) -> EnforcementObservation:
    # Bus unavailable: fail closed to the narrower known scope, never the
    # shim cache, because the shim is the component that can widen.
    if bus is None:
        if shim is None:
            raise ScopeDecouplingError(
                f"no enforcement observation available for {action!r}; "
                "refusing to proceed unverified"
            )
        if shim.allowed:
            raise ScopeDecouplingError(
                f"bus enforcement unavailable for {action!r} while shim "
                f"permits it under generation {shim.warrant_generation}; "
                "fail closed rather than trust the widening-prone shim"
            )
        return shim

    if shim is None:
        raise ScopeDecouplingError(
            f"shim enforcement missing for {action!r} but bus reported "
            f"generation {bus.warrant_generation}; enforcement points "
            "are not both live"
        )

    # Disagreement on allow/deny is never transient; halt.
    if shim.allowed != bus.allowed:
        raise ScopeDecouplingError(
            f"allow/deny divergence for {action!r}: shim={shim.allowed} "
            f"(gen {shim.warrant_generation}), bus={bus.allowed} "
            f"(gen {bus.warrant_generation})"
        )

    # Agreement on allow is necessary but not sufficient: generations
    # must match, or the two points are evaluating different warrants.
    if shim.warrant_generation != bus.warrant_generation:
        raise ScopeDecouplingError(
            f"warrant generation skew for {action!r}: shim="
            f"{shim.warrant_generation}, bus={bus.warrant_generation}; "
            "re-derive scope from issuer before resuming"
        )

    return bus


def invoke_tool(action: str, shim_obs, bus_obs) -> str:
    decision = reconcile_enforcement(action, shim_obs, bus_obs)
    if not decision.allowed:
        raise ScopeDecouplingError(
            f"action {action!r} denied by both enforcement points at "
            f"generation {decision.warrant_generation}"
        )
    return f"executed {action!r} under generation {decision.warrant_generation}"
