# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-delegated-scope-attenuation-when-a-capability-token-s-subject-chain-crosses-a-workload-identity-re-mint-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-delegated-scope-attenuation-when-a-capability-token-s-subject-chain-crosses-a-workload-identity-re-mint-boundary.warrant.json
# Markdown SHA-256:   c0bae5ff771d0f7153671f0472f2ba9c2c2b9da674e71d06578f15482b758ce3
# Code AST SHA-256:   9998727cbc7799454b887df4836a401c93a09b564cf045b3ba5fa2a377d92f9e
# Verified Classes:   StaleEpochDelegation, CapabilityToken, LiveWorkloadIdentity
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class StaleEpochDelegation(RuntimeError):
    """Raised when a capability token's delegated scope is bound to a WI
    epoch that no longer matches the presenting workload's live epoch."""


@dataclass(frozen=True)
class CapabilityToken:
    subject_name: str
    subject_epoch: str          # epoch under which the scope was delegated
    scope_chain: tuple[str, ...]
    attestation_class: str


@dataclass(frozen=True)
class LiveWorkloadIdentity:
    name: str
    epoch: str
    attestation_class: str


def authorize_tool_call(
    token: CapabilityToken,
    live_wi: LiveWorkloadIdentity,
    *,
    allow_reanchor_within_class: bool = False,
) -> str:
    # Name match alone is the exact comparison that produces the silent
    # scope-continuity break. Require epoch equality.
    if token.subject_name != live_wi.name:
        raise StaleEpochDelegation(
            f"subject name mismatch: token={token.subject_name!r} "
            f"live={live_wi.name!r}"
        )

    if token.subject_epoch == live_wi.epoch:
        return "authorized"

    # Epochs differ: a WI re-mint boundary has been crossed.
    if (
        allow_reanchor_within_class
        and token.attestation_class == live_wi.attestation_class
    ):
        # Same attestation class: re-anchoring is permitted, but must be
        # logged by the caller as an epoch transition.
        return "reanchored"

    raise StaleEpochDelegation(
        "delegated scope bound to stale workload-identity epoch: "
        f"token_epoch={token.subject_epoch!r} live_epoch={live_wi.epoch!r} "
        f"token_class={token.attestation_class!r} "
        f"live_class={live_wi.attestation_class!r}"
    )
