# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-enforcement-when-a-delegated-agent-chain-re-derives-scope-from-capability-names-instead-of-from-signed-warra.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-enforcement-when-a-delegated-agent-chain-re-derives-scope-from-capability-names-instead-of-from-signed-warra.warrant.json
# Markdown SHA-256:   f73830e75ea5c29e6f059efd7b9e12e3204ef0a1f70a343cbd2477adfe227c7f
# Code AST SHA-256:   c8202853818cf23c6a7790d756a3595ea05b63dbd193c633c3071fc7e03becca
# Verified Classes:   WarrantScopeViolation, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantScopeViolation(RuntimeError):
    """Raised when a tool call's target/action is not covered by the leaf warrant,
    or when the attenuation chain is invalid. Must fail closed — never fall back
    to capability-name matching."""


@dataclass(frozen=True)
class Warrant:
    principal: str
    resources: FrozenSet[str]
    actions: FrozenSet[str]
    expiry: float
    parent_hash: str | None
    self_hash: str


def _subset(child: Warrant, parent: Warrant) -> bool:
    return (
        child.resources <= parent.resources
        and child.actions <= parent.actions
        and child.expiry <= parent.expiry
        and child.parent_hash == parent.self_hash
    )


def authorize_tool_call(
    *,
    capability_name: str,          # routing/logging only — MUST NOT affect decision
    leaf: Warrant,
    chain: list[Warrant],           # root .. leaf, inclusive
    target_resource: str,
    action: str,
    now: float,
    trusted_root_hash: str,
) -> None:
    # 1. Chain must be well-formed and rooted in a trusted warrant.
    if not chain or chain[-1].self_hash != leaf.self_hash:
        raise WarrantScopeViolation("leaf warrant does not match chain tail")
    if chain[0].self_hash != trusted_root_hash:
        raise WarrantScopeViolation(
            f"chain root {chain[0].self_hash!r} not trusted"
        )
    # 2. Every hop must monotonically attenuate its parent.
    for parent, child in zip(chain, chain[1:]):
        if not _subset(child, parent):
            raise WarrantScopeViolation(
                f"attenuation violated: {child.self_hash} widens {parent.self_hash}"
            )
    # 3. Expiry enforced against the leaf, not the root.
    if now > leaf.expiry:
        raise WarrantScopeViolation(
            f"leaf warrant expired at {leaf.expiry}, now={now}"
        )
    # 4. Scope enforced against the leaf warrant ONLY.
    #    capability_name is deliberately not consulted.
    if target_resource not in leaf.resources:
        raise WarrantScopeViolation(
            f"resource {target_resource!r} not in leaf scope "
            f"{sorted(leaf.resources)} (capability_name={capability_name!r} ignored)"
        )
    if action not in leaf.actions:
        raise WarrantScopeViolation(
            f"action {action!r} not in leaf scope "
            f"{sorted(leaf.actions)} (capability_name={capability_name!r} ignored)"
        )


def invoke_tool(runtime, request) -> None:
    authorize_tool_call(
        capability_name=request.capability_name,
        leaf=request.warrant,
        chain=request.chain,
        target_resource=request.target,
        action=request.action,
        now=runtime.clock.now(),
        trusted_root_hash=runtime.trust_anchor,
    )
    runtime.execute(request)
