# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-inherit-a-delegated-scope-it-can-never-legally-exercise-the-attenuation-capability-mismatch-in-aaif-verifiable-credentials.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-inherit-a-delegated-scope-it-can-never-legally-exercise-the-attenuation-capability-mismatch-in-aaif-verifiable-credentials.warrant.json
# Markdown SHA-256:   b55fb3748cffe3fa2aeeb2f82509b96fb3ccb77e2fba9102bb34745608796c42
# Code AST SHA-256:   b3e1937fa72ed8a5e535f7a1e0619dd69fe314ecd15d7f28ed084d8196ac7214
# Verified Classes:   UnsatisfiableScope, Scope, Credential, Runtime
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class UnsatisfiableScope(RuntimeError):
    """Raised when a delegated scope cannot be discharged by the subject's capabilities."""
    pass


@dataclass(frozen=True)
class Scope:
    predicates: FrozenSet[str]

    def __le__(self, other: "Scope") -> bool:
        return self.predicates <= other.predicates

    def __and__(self, other: "Scope") -> "Scope":
        return Scope(self.predicates & other.predicates)


@dataclass(frozen=True)
class Credential:
    subject_did: str
    delegated_scope: Scope
    capability_digest: str
    stale: bool = False


@dataclass
class Runtime:
    did: str
    bound_tools: FrozenSet[str] = field(default_factory=frozenset)

    def capability_scope(self) -> Scope:
        return Scope(self.bound_tools)


def authorize_task(cred: Credential, runtime: Runtime, task_required: Scope) -> Scope:
    if cred.stale:
        raise UnsatisfiableScope(
            f"credential for {cred.subject_did} is stale; capability manifest drifted"
        )
    if cred.subject_did != runtime.did:
        raise UnsatisfiableScope(
            f"credential subject {cred.subject_did} != runtime {runtime.did}"
        )

    effective = cred.delegated_scope & runtime.capability_scope()

    if not effective.predicates:
        raise UnsatisfiableScope(
            f"empty intersection: delegated {sorted(cred.delegated_scope.predicates)} "
            f"vs capability {sorted(runtime.capability_scope().predicates)}"
        )

    if not task_required <= effective:
        missing = task_required.predicates - effective.predicates
        raise UnsatisfiableScope(
            f"task requires {sorted(missing)} not dischargeable by {runtime.did}; "
            f"delegated claim {sorted(cred.delegated_scope.predicates)} "
            f"exceeds bound tools {sorted(runtime.bound_tools)}"
        )

    return effective


# Reproduces the observed failure: W holds pii:read in its credential but has no pii tool bound.
w_cred = Credential(
    subject_did="did:aaif:worker-w",
    delegated_scope=Scope(frozenset({"refunds:<=100", "pii:read"})),
    capability_digest="sha256:...",
)
w_runtime = Runtime(did="did:aaif:worker-w", bound_tools=frozenset({"refunds", "orders:read"}))

try:
    authorize_task(w_cred, w_runtime, Scope(frozenset({"refunds:<=100", "pii:read"})))
except UnsatisfiableScope as e:
    print(f"HALT: {e}")
    # HALT: task requires ['pii:read'] not dischargeable by did:aaif:worker-w;
    # delegated claim ['pii:read', 'refunds:<=100'] exceeds bound tools ['orders:read', 'refunds']
