# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-chain-has-silently-re-scoped-below-its-root-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-credential-chain-has-silently-re-scoped-below-its-root-grant.warrant.json
# Markdown SHA-256:   b59a8cf844ca570be297f049aaef6950bc17e5766aafde12227d80cb0f9733d9
# Code AST SHA-256:   165cb7ba455cbec228bdd272e74801dac7892f3a262dbca7b3e6f72075d9e3f2
# Verified Classes:   CaveatStrippingError, Link
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CaveatStrippingError(RuntimeError):
    """Raised when a delegated chain's leaf does not entail an ancestor caveat."""
    pass


@dataclass(frozen=True)
class Link:
    issuer: str
    subject: str
    declared_scope: FrozenSet[str]
    caveats: FrozenSet[str]
    signature_valid: bool


def entails(leaf_caveats: FrozenSet[str], ancestor_caveats: FrozenSet[str]) -> bool:
    # A caveat is entailed if it is present at the leaf, or if the leaf
    # carries a strictly stronger caveat that subsumes it. Here we model
    # subsumption conservatively: only exact presence counts as entailment.
    # Callers with a caveat algebra should override this.
    return ancestor_caveats.issubset(leaf_caveats)


def verify_composed_chain(chain: list[Link]) -> None:
    if not chain:
        raise CaveatStrippingError("empty chain")

    # 1. Per-link signature and immediate scope subset.
    for i, link in enumerate(chain):
        if not link.signature_valid:
            raise CaveatStrippingError(f"link {i} signature invalid at {link.issuer}")
        if i > 0:
            parent = chain[i - 1]
            if not link.declared_scope.issubset(parent.declared_scope):
                raise CaveatStrippingError(
                    f"link {i} scope {link.declared_scope} not subset of parent {parent.declared_scope}"
                )

    # 2. Transitive caveat entailment: leaf must entail every ancestor caveat.
    root = chain[0]
    leaf = chain[-1]
    if len(chain) > 1 and not entails(leaf.caveats, root.caveats):
        missing = root.caveats - leaf.caveats
        raise CaveatStrippingError(
            f"caveat stripping detected: leaf {leaf.subject} does not entail "
            f"root caveats {missing}; chain length {len(chain)}"
        )

    # 3. Effective-scope intersection must nest under root effective scope.
    #    (Declared-scope subset checks above are necessary but not sufficient.)
    effective_root = root.declared_scope
    effective_leaf = leaf.declared_scope
    if not effective_leaf.issubset(effective_root):
        raise CaveatStrippingError(
            f"effective scope escape: leaf {effective_leaf} not under root {effective_root}"
        )


def authorize_tool_call(chain: list[Link], resource: str) -> bool:
    verify_composed_chain(chain)
    leaf = chain[-1]
    return resource in leaf.declared_scope
