# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-aaif-credential-rather-than-forward-it-intact.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-aaif-credential-rather-than-forward-it-intact.warrant.json
# Markdown SHA-256:   8ac27f5c1b997e494abe98263566ab88193eec2b97030d5b1db11d6815306495
# Code AST SHA-256:   bf466ca1207f4d528c704bf176969d6acc9a6677f9abbc27c280065a0f45fe36
# Verified Classes:   DelegationScopeViolation, Credential, ChildTask
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeViolation(RuntimeError):
    """Raised when a forwarded credential would grant a child more authority
    than its declared need, requiring re-derivation instead of forwarding."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str
    scope: FrozenSet[str]
    delegated_by: str
    nonce: str


@dataclass
class ChildTask:
    agent_id: str
    declared_need: FrozenSet[str]
    reasoning_driven: bool = True  # LLM selects tools over discovered affordances


def delegate(parent_cred: Credential, child: ChildTask, parent_signer) -> Credential:
    # Condition 1: is the parent's scope a subset of what the child could need?
    residual = parent_cred.scope - child.declared_need
    # Condition 2: is the child a deterministic consumer?
    # Condition 3: does the credential carry a per-call attenuation proof?
    # If residual authority exists AND the child reasons over affordances,
    # forwarding intact is unsafe -> must re-derive.
    if residual and child.reasoning_driven:
        narrowed = parent_cred.scope & child.declared_need
        if not narrowed:
            raise DelegationScopeViolation(
                f"child {child.agent_id} declares need {sorted(child.declared_need)} "
                f"which does not intersect parent scope {sorted(parent_cred.scope)}; "
                f"cannot mint a non-empty delegated credential"
            )
        return Credential(
            subject=child.agent_id,
            scope=frozenset(narrowed),
            delegated_by=parent_cred.subject,
            nonce=parent_signer.new_nonce(),
        )
    # Safe to forward: no residual authority to leak, or child is deterministic.
    return parent_cred
