# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-privilege-re-expansion-in-agent-to-agent-delegation-chains-when-attenuated-warrants-are-re-minted-across-heterogeneous-runtim.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-privilege-re-expansion-in-agent-to-agent-delegation-chains-when-attenuated-warrants-are-re-minted-across-heterogeneous-runtim.warrant.json
# Markdown SHA-256:   e60c444e0ff48adfe5d74ccb6ffd614b5a171897fdb79544dbfcce62ea2e1409
# Code AST SHA-256:   ad874f7577e5991040b043737cafaca7e71d91bbbecc713690a98dc3c76916f7
# Verified Classes:   LineageAttenuationError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class LineageAttenuationError(RuntimeError):
    """Raised when a re-minted warrant's lineage would re-expand effective privilege."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    root_id: str
    parent_id: str | None
    parent_hash: str | None
    scope: frozenset[str]
    signed_payload: bytes  # canonical bytes over (root_id, parent_hash, scope)


def _hash(w: Warrant) -> str:
    return hashlib.sha256(w.signed_payload).hexdigest()


def re_mint(parent: Warrant, child_scope: frozenset[str], *, from_summary: bool) -> Warrant:
    if from_summary:
        # Re-minting from a distilled representation cannot preserve signed bytes.
        raise LineageAttenuationError(
            f"re-mint of {parent.warrant_id} derived from summary, not signed payload; "
            "root binding cannot be verified"
        )
    if not child_scope.issubset(parent.scope):
        raise LineageAttenuationError(
            f"scope {child_scope} not subset of parent {parent.scope}"
        )
    payload = f"{parent.root_id}|{_hash(parent)}|{sorted(child_scope)}".encode()
    return Warrant(
        warrant_id=f"{parent.warrant_id}.c",
        root_id=parent.root_id,
        parent_id=parent.warrant_id,
        parent_hash=_hash(parent),
        scope=child_scope,
        signed_payload=payload,
    )


def resolve_effective_authority(chain: list[Warrant], root: Warrant) -> frozenset[str]:
    """Authority is scope(leaf) ALONE. Ancestor scopes are attribution-only."""
    leaf = chain[-1]
    if leaf.root_id != root.root_id:
        raise LineageAttenuationError("leaf root binding does not match root principal")
    # Walk for provenance verification, but never fold into effective set.
    for parent, child in zip(chain, chain[1:]):
        if child.parent_hash != _hash(parent):
            raise LineageAttenuationError(
                f"lineage break: {child.warrant_id} parent_hash mismatch"
            )
        if not child.scope.issubset(parent.scope):
            raise LineageAttenuationError(
                f"attenuation violated at {child.warrant_id}"
            )
    return leaf.scope  # no union, no max, no fold


def admit(chain: list[Warrant], root: Warrant, requested: frozenset[str]) -> bool:
    effective = resolve_effective_authority(chain, root)
    if not requested.issubset(effective):
        raise LineageAttenuationError(
            f"request {requested} exceeds effective authority {effective}"
        )
    return True
