# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-warrant-it-cannot-re-derive-credential-chain-re-binding-failure-in-aaif-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-warrant-it-cannot-re-derive-credential-chain-re-binding-failure-in-aaif-agent-handoffs.warrant.json
# Markdown SHA-256:   23bbceb94c523b2a86484faad9557dd41d6853ba0164a801d57ad95b2c0c5b9b
# Code AST SHA-256:   6465010dfa1476b850902e1bf2031ce01130a2798999129c07d5625b555e6bc7
# Verified Classes:   ChainDerivationError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable


class ChainDerivationError(RuntimeError):
    """Raised when an AAIF credential chain cannot be re-derived to its root."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    scope: str
    attenuation_semantics: str  # hash/id of the normalization used vs. parent
    signature_valid: bool = True


# Verifier's closed set of implemented attenuation semantics.
SUPPORTED_SEMANTICS: dict[str, Callable[[str, str], bool]] = {
    "prefix-v1": lambda child, parent: child == parent or child.startswith(parent.rstrip("/") + "/"),
}


def rederive_chain(chain: list[Warrant], root_scope: str) -> str:
    """
    Fold committed attenuations from the root grant down to the leaf.
    Returns the reconstructed effective leaf scope, or raises ChainDerivationError.
    """
    if not chain:
        raise ChainDerivationError("empty chain: no root anchor to derive from")

    effective = root_scope
    for hop_index, hop in enumerate(chain):
        semantics = SUPPORTED_SEMANTICS.get(hop.attenuation_semantics)
        if semantics is None:
            # Uncommitted or unimplemented semantics: the hop is unreconstructible.
            # Do NOT fall back to our own normalization.
            raise ChainDerivationError(
                f"hop {hop_index} ({hop.issuer}->{hop.subject}): "
                f"attenuation semantics {hop.attenuation_semantics!r} not implemented; "
                f"chain unreconstructible, treat as absent"
            )
        if not hop.signature_valid:
            raise ChainDerivationError(f"hop {hop_index}: invalid signature")
        if not semantics(hop.scope, effective):
            # Decidable, but the child exceeds the reconstruction: escalation, not mismatch.
            raise ChainDerivationError(
                f"hop {hop_index} ({hop.issuer}->{hop.subject}): "
                f"scope {hop.scope!r} exceeds reconstructed parent scope {effective!r} "
                f"under committed semantics {hop.attenuation_semantics!r}; quarantine issuer"
            )
        effective = hop.scope

    return effective


def authorize_tool_call(chain: list[Warrant], root_scope: str, requested_path: str) -> None:
    leaf_scope = rederive_chain(chain, root_scope)
    if not SUPPORTED_SEMANTICS["prefix-v1"](requested_path, leaf_scope):
        raise ChainDerivationError(
            f"requested path {requested_path!r} outside reconstructed leaf scope {leaf_scope!r}"
        )


if __name__ == "__main__":
    # Hop 2 was minted by an instance using a `/**`-collapsing normalization
    # not committed in a form the verifier implements.
    chain = [
        Warrant("agent:A", "root", "/workspace/project-a", "prefix-v1"),
        Warrant("agent:B", "agent:A", "/workspace/project-a/src/parsers", "glob-collapse-v0"),
    ]
    try:
        authorize_tool_call(chain, "/workspace/project-a", "/workspace/project-a/src/parsers/x.py")
    except ChainDerivationError as e:
        print(f"REJECTED: {e}")
