# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-delegated-capability-tokens-when-the-delegation-chain-outlives-the-issuing-agent-s-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-delegated-capability-tokens-when-the-delegation-chain-outlives-the-issuing-agent-s-context-window.warrant.json
# Markdown SHA-256:   eb35edeb2e7b222df527424d8e4f249b8b7b0253c9f11e8a161388e8376ef3d0
# Code AST SHA-256:   7d6d501d64483ba96af008dbf4b0c347c3ba8c83d318221ddd622cce4a9ef2ed
# Verified Classes:   DelegationAttenuationError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationAttenuationError(RuntimeError):
    """Raised when a child scope is not provably a subset of its parent scope."""
    pass


@dataclass(frozen=True)
class Scope:
    resource: str
    actions: frozenset
    predicates: frozenset  # e.g. frozenset({("argv0", "grep"), ("argv0", "sed")})

    def digest(self) -> str:
        blob = repr((self.resource, sorted(self.actions), sorted(self.predicates)))
        return hashlib.sha256(blob.encode()).hexdigest()


def is_subset(child: Scope, parent: Scope) -> bool:
    if child.resource != parent.resource:
        return False
    if not child.actions.issubset(parent.actions):
        return False
    # Every child predicate must be implied by some parent predicate.
    return child.predicates.issubset(parent.predicates)


def issue_delegated(parent_scope: Scope, parent_digest: str, child_scope: Scope) -> dict:
    """Issue a child token only if the parent scope is carried verbatim.

    parent_digest is the hash the issuer must reproduce from the *actual*
    parent scope bytes it holds. If the issuer only has a summary, it cannot
    reproduce the digest and must not delegate.
    """
    if parent_scope.digest() != parent_digest:
        raise DelegationAttenuationError(
            f"Parent scope digest mismatch: issuer holds {parent_scope.digest()!r} "
            f"but token chain expects {parent_digest!r}. Issuer is reconstructing "
            f"from a lossy summary; delegation aborted to prevent authority widening."
        )
    if not is_subset(child_scope, parent_scope):
        raise DelegationAttenuationError(
            f"Child scope {child_scope!r} is not a subset of parent {parent_scope!r}; "
            f"attenuation invariant S_child <= S_parent violated."
        )
    return {
        "child_scope": child_scope,
        "parent_digest": parent_digest,
        "child_digest": child_scope.digest(),
    }


def verify_chain(tokens: list) -> bool:
    """Recompute the intersection chain at validation time."""
    for tok in tokens:
        if tok["child_scope"].digest() != tok["child_digest"]:
            raise DelegationAttenuationError("Child scope bytes do not match signed digest.")
    return True
