# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-chain-collapse-when-an-aaif-sub-agent-attenuates-scope-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-chain-collapse-when-an-aaif-sub-agent-attenuates-scope-mid-execution.warrant.json
# Markdown SHA-256:   35281769dec0f91677243ad0cd7a25d65d1e34b63b63155a2fa7dbf6453ee730
# Code AST SHA-256:   3b17ab4db0723eb4b3b4210017864f36377b9379f2750e67060e165fe2f2871c
# Verified Classes:   ChainProvenanceError, ParentRef, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import base64
from dataclasses import dataclass
from typing import Optional


class ChainProvenanceError(RuntimeError):
    """Raised when a delegated warrant's parent reference cannot be bound to a
    verifiable issuer key identifier. Fail-closed; never fall back to name lookup."""


@dataclass(frozen=True)
class ParentRef:
    issuer_kid: Optional[str]
    raw_envelope_b64: Optional[str]
    subject_name: str  # present for human readability ONLY; never used for key resolution


@dataclass(frozen=True)
class Warrant:
    scope: frozenset
    delegation_depth_max: int
    parent: Optional[ParentRef]


def attenuate(parent: Warrant, child_scope: frozenset, parent_raw_b64: str) -> Warrant:
    """Emit a child warrant. The parent's raw signed bytes MUST be supplied from an
    out-of-context store; we never reconstruct them from the agent's context."""
    if not parent_raw_b64:
        raise ChainProvenanceError(
            "cannot attenuate: parent raw envelope missing from credential store; "
            "refusing to reconstruct from context summary"
        )
    if parent.parent is not None and not parent.parent.issuer_kid:
        raise ChainProvenanceError(
            f"parent warrant for subject {parent.parent.subject_name!r} has no issuer_kid; "
            "name-based key resolution is forbidden in chain verification"
        )
    if not child_scope.issubset(parent.scope):
        raise ChainProvenanceError(
            f"scope escalation: {child_scope - parent.scope} not held by parent"
        )
    if parent.delegation_depth_max <= 0:
        raise ChainProvenanceError("delegation depth exhausted; cannot attenuate further")
    return Warrant(
        scope=child_scope,
        delegation_depth_max=parent.delegation_depth_max - 1,
        parent=ParentRef(
            issuer_kid=parent.parent.issuer_kid if parent.parent else "ROOT_KID",
            raw_envelope_b64=parent_raw_b64,
            subject_name=parent.parent.subject_name if parent.parent else "root",
        ),
    )


def verify_chain(child: Warrant, key_fetch) -> bool:
    """Verify a child against its parent by kid-bound key fetch only."""
    if child.parent is None:
        raise ChainProvenanceError("orphan warrant: no parent reference")
    if not child.parent.issuer_kid:
        raise ChainProvenanceError(
            "missing issuer_kid in parent reference; cannot bind to a key"
        )
    raw = base64.b64decode(child.parent.raw_envelope_b64 or "")
    if not raw:
        raise ChainProvenanceError("empty parent envelope; provenance truncated")
    key = key_fetch(child.parent.issuer_kid)
    if key is None:
        raise ChainProvenanceError(
            f"unknown issuer_kid {child.parent.issuer_kid!r}; fail closed, no name fallback"
        )
    return key.verify(raw)
