# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-tool-call-authority-from-surviving-a-re-signed-audit-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-tool-call-authority-from-surviving-a-re-signed-audit-hop.warrant.json
# Markdown SHA-256:   13e6ae8f527dccc667d2d93627deef69537422d0f51456e74941842d0c8cec46
# Code AST SHA-256:   f6be2b6bf7c5c025ff92e066e07a97a4d79ce505a3ac681f12f5d9b11e864cb0
# Verified Classes:   AuthorityLaunderingError, AuditHop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AuthorityLaunderingError(RuntimeError):
    """Raised when a hop's inbound scope is grantee-attested rather than grantor-attested."""


@dataclass(frozen=True)
class AuditHop:
    grantor: str
    grantee: str
    inbound_scope: frozenset[str]
    inbound_scope_attested_by: str      # who populated the inbound_scope field
    inbound_commitment: str | None      # hash bound into grantor's signed record, if any
    outbound_scope: frozenset[str]


def _commit(scope: frozenset[str]) -> str:
    return hashlib.sha256(b"|".join(sorted(scope))).hexdigest()


def verify_delegation_chain(hops: list[AuditHop], root_scope: frozenset[str]) -> frozenset[str]:
    effective = root_scope
    for hop in hops:
        # Invariant: inbound scope must be attested by the grantor AND hash-bound
        # into the grantor's own signed record. Grantee self-attestation is laundering.
        if hop.inbound_scope_attested_by != hop.grantor:
            raise AuthorityLaunderingError(
                f"hop {hop.grantor}->{hop.grantee}: inbound scope attested by "
                f"{hop.inbound_scope_attested_by}, not grantor {hop.grantor}"
            )
        if hop.inbound_commitment is None or hop.inbound_commitment != _commit(hop.inbound_scope):
            raise AuthorityLaunderingError(
                f"hop {hop.grantor}->{hop.grantee}: inbound scope not hash-bound to grantor record"
            )
        # Recompute effective authority from grantor-attested bytes, not grantee claims.
        if not hop.inbound_scope <= effective:
            raise AuthorityLaunderingError(
                f"hop {hop.grantor}->{hop.grantee}: inbound scope exceeds recomputed authority"
            )
        if not hop.outbound_scope <= hop.inbound_scope:
            raise AuthorityLaunderingError(
                f"hop {hop.grantor}->{hop.grantee}: outbound scope exceeds inbound grant"
            )
        effective = hop.outbound_scope
    return effective


def authorize_terminal_call(hops: list[AuditHop], root_scope: frozenset[str],
                            requested: frozenset[str]) -> None:
    effective = verify_delegation_chain(hops, root_scope)
    if not requested <= effective:
        raise AuthorityLaunderingError(
            f"terminal call requests {sorted(requested - effective)} beyond recomputed authority"
        )
