# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attenuation-depth-collapse-from-silently-widening-delegated-authority-in-agent-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attenuation-depth-collapse-from-silently-widening-delegated-authority-in-agent-chains.warrant.json
# Markdown SHA-256:   5ba69d85642c056df8a9c8034d8695d14b2f7527131cf2449c289c79d1eaa8c7
# Code AST SHA-256:   49cac442ba8a3e5f2ca725fbf75a150f61916a40bdb413940dd120be3a1009bd
# Verified Classes:   AttenuationCollapse, Scope, Token
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional

class AttenuationCollapse(RuntimeError):
    """Raised when a minted child token's enforced scope diverges from the
    fold-of-intersections from the root, i.e. attenuation-depth collapse."""
    pass

@dataclass(frozen=True)
class Scope:
    resources: frozenset
    budget: int
    window: tuple  # (start, end) in seconds, coarse

    def intersect(self, other: "Scope") -> "Scope":
        return Scope(
            resources=self.resources & other.resources,
            budget=min(self.budget, other.budget),
            window=(max(self.window[0], other.window[0]),
                    min(self.window[1], other.window[1])),
        )

    def fold_hash(self) -> str:
        blob = repr((sorted(self.resources), self.budget, self.window)).encode()
        return hashlib.sha256(blob).hexdigest()

@dataclass
class Token:
    scope: Scope
    fold_commitment: str
    parent_fold: Optional[str] = None

def mint_child(parent: Token, requested: Scope, root_fold: str) -> Token:
    """Mint an attenuated child. Enforces fold-equivalence: the child's
    enforced scope must equal parent.scope ∩ requested, AND the committed
    fold from the root must recompute. Refuses mint from stale audit records."""
    enforced = parent.scope.intersect(requested)

    # Recompute the fold from the root through the parent's commitment.
    expected_fold = hashlib.sha256(
        (root_fold + enforced.fold_hash()).encode()
    ).hexdigest()

    if parent.fold_commitment != root_fold and parent.fold_commitment is None:
        raise AttenuationCollapse(
            f"parent token lacks fold commitment; cannot bound depth at "
            f"resources={sorted(enforced.resources)}"
        )

    # Guard: if the parent was rehydrated from an audit record, its scope
    # may be a coarsened normalization. Detect by checking that the child's
    # enforced scope is a strict subset of the parent's raw requested scope.
    if enforced.window != (max(parent.scope.window[0], requested.window[0]),
                           min(parent.scope.window[1], requested.window[1])):
        raise AttenuationCollapse(
            f"window fold mismatch: enforced={enforced.window} "
            f"parent={parent.scope.window} requested={requested.window}"
        )

    if enforced.budget > parent.scope.budget:
        raise AttenuationCollapse(
            f"budget widened at mint: enforced={enforced.budget} "
            f"parent={parent.scope.budget}"
        )

    return Token(scope=enforced, fold_commitment=expected_fold,
                 parent_fold=parent.fold_commitment)

def resume_from_audit(recorded_scope: Scope, requested: Scope,
                      root_fold: str) -> Token:
    """Resuming from an audit record is the collapse-prone path. We refuse
    to treat the record as a parent; we require re-derivation from root."""
    synthetic_parent = Token(scope=recorded_scope,
                             fold_commitment=root_fold,
                             parent_fold=None)
    try:
        return mint_child(synthetic_parent, requested, root_fold)
    except AttenuationCollapse as e:
        raise AttenuationCollapse(
            f"refusing resume-from-record: recorded scope cannot serve as "
            f"authorizing parent ({e}); re-derive from root token instead"
        )
