# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-mid-chain-scope-narrowing-non-composition-in-aaif-capability-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-mid-chain-scope-narrowing-non-composition-in-aaif-capability-tokens.warrant.json
# Markdown SHA-256:   6ef5129c8216e1c8461eec851bd8572b67f9732c93b8e07295cde6b0f90d7d51
# Code AST SHA-256:   f33733fa589d3f2c8220653176865b7b2ad1cccfbb6ac5e16773cc397f3ab708
# Verified Classes:   ScopeResolutionIncomplete, HopGrant, Gateway
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ScopeResolutionIncomplete(RuntimeError):
    """Raised when an ancestor constraint in a delegation chain cannot be
    resolved within the gateway budget, and the gateway is about to
    fail-closed to a default that is indistinguishable from a real denial."""
    pass


@dataclass
class HopGrant:
    hop_id: str
    tool: str
    constraint: dict
    ancestor_hash: str | None = None  # pointer to parent envelope, or None at root
    inlined_ancestor: dict | None = None  # present iff issuer chose inline mode


@dataclass
class Gateway:
    envelope_cache: dict = field(default_factory=dict)
    budget_ms: int = 40

    def resolve_conjunction(self, grant: HopGrant, chain: list[HopGrant]) -> dict:
        """Compute effective constraint as conjunction over hops 1..n.
        Must be TOTAL: every ancestor resolvable, or raise distinctly."""
        effective = dict(grant.constraint)
        cursor = grant
        while cursor.ancestor_hash is not None:
            parent = self.envelope_cache.get(cursor.ancestor_hash)
            if parent is None:
                if cursor.inlined_ancestor is not None:
                    parent = cursor.inlined_ancestor
                else:
                    # DO NOT default to row_limit:0 -- that is a valid deny-all
                    # value and is indistinguishable from a genuine denial.
                    raise ScopeResolutionIncomplete(
                        f"ancestor {cursor.ancestor_hash} unresolvable for "
                        f"tool={grant.tool} within {self.budget_ms}ms; "
                        f"refusing to fail-closed to a zero constraint"
                    )
            effective = _conjoin(effective, parent)
            cursor = next((h for h in chain if h.hop_id == cursor.ancestor_hash), None)
            if cursor is None:
                raise ScopeResolutionIncomplete(
                    f"chain broken: no hop record for ancestor "
                    f"{grant.ancestor_hash}"
                )
        return effective


def _conjoin(a: dict, b: dict) -> dict:
    """Monotone intersection: tighter row_limit wins, allow-lists intersect."""
    out = dict(a)
    if "row_limit" in a and "row_limit" in b:
        out["row_limit"] = min(a["row_limit"], b["row_limit"])
    if "table_allow" in a and "table_allow" in b:
        out["table_allow"] = sorted(set(a["table_allow"]) & set(b["table_allow"]))
    elif "table_allow" in b:
        out["table_allow"] = b["table_allow"]
    return out


def authorize(gateway: Gateway, grant: HopGrant, chain: list[HopGrant], request: dict) -> bool:
    eff = gateway.resolve_conjunction(grant, chain)
    if eff.get("row_limit", 0) <= 0:
        return False
    if "table_allow" in eff and request.get("table") not in eff["table_allow"]:
        return False
    return True
