# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-a-scoped-aaif-capability-token-and-why-does-silent-scope-inheritance-break-the-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-a-scoped-aaif-capability-token-and-why-does-silent-scope-inheritance-break-the-delegation-chain.warrant.json
# Markdown SHA-256:   4503e2a965dfee4f76245b51626e37c49eafd29db7ddd69d24779c371e35abde
# Code AST SHA-256:   b88ebdd49272928e33c994bb0e3bb36ba90b8913ce16894c988316572b3c4e99
# Verified Classes:   ScopeInheritanceError, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeInheritanceError(RuntimeError):
    """Raised when an instance attempts to forward or use an AAIF scoped
    capability token whose scope was inherited rather than re-derived
    against the current task's declared action set."""


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    delegation_chain: tuple = field(default_factory=tuple)
    no_attenuation_warrant: bool = False


def rederive_for_delegation(
    parent: CapabilityToken,
    child_subject: str,
    child_intended_actions: FrozenSet[str],
) -> CapabilityToken:
    """Re-derive a child token by intersecting parent scope with the child's
    declared action set. Refuses to forward unchanged scope without a warrant."""
    if not child_intended_actions:
        raise ScopeInheritanceError(
            f"child {child_subject!r} declared no action set; cannot justify any scope"
        )
    if not child_intended_actions.issubset(parent.scope):
        excess = child_intended_actions - parent.scope
        raise ScopeInheritanceError(
            f"child {child_subject!r} requires {sorted(excess)} outside parent scope "
            f"{sorted(parent.scope)}; widening requires root warrant"
        )
    if child_intended_actions == parent.scope and not parent.no_attenuation_warrant:
        # Unchanged scope is a missing re-derivation upstream, not a valid hop.
        raise ScopeInheritanceError(
            f"refusing unchanged-scope hop {parent.subject!r} -> {child_subject!r}: "
            f"no attenuation warrant in chain {parent.delegation_chain!r}"
        )
    return CapabilityToken(
        subject=child_subject,
        scope=child_intended_actions,
        delegation_chain=parent.delegation_chain + ((parent.subject, child_subject),),
        no_attenuation_warrant=False,
    )


def resume_from_checkpoint(
    serialized: CapabilityToken,
    resumed_task_actions: FrozenSet[str],
) -> CapabilityToken:
    """On resume, re-derive against the resumed task descriptor, never against
    the serialized token. A serialized token is a scope, not a task."""
    if resumed_task_actions is None:
        raise ScopeInheritanceError(
            f"resume of {serialized.subject!r} has no task descriptor; "
            f"cannot justify scope {sorted(serialized.scope)}"
        )
    if not resumed_task_actions.issubset(serialized.scope):
        raise ScopeInheritanceError(
            f"resumed task for {serialized.subject!r} needs "
            f"{sorted(resumed_task_actions - serialized.scope)} not in serialized scope"
        )
    return CapabilityToken(
        subject=serialized.subject,
        scope=resumed_task_actions,
        delegation_chain=serialized.delegation_chain,
        no_attenuation_warrant=False,
    )
