# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-scope-laundering-across-federated-trust-boundaries-when-a-delegated-agent-re-signs-a-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-scope-laundering-across-federated-trust-boundaries-when-a-delegated-agent-re-signs-a-warrant.warrant.json
# Markdown SHA-256:   28e22fab48e937f8bd4d038a059781d2a1d9479d09afc074cd76a9703f5ff0d1
# Code AST SHA-256:   99906cf09ddf1eb12f51684bb46f16aa4a87a18de125b44361d73a7bd757f419
# Verified Classes:   ScopeLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ScopeLaunderingError(RuntimeError):
    """Raised when a delegated warrant's scope is not a subset of its parent's scope."""
    pass


def mint_child_warrant(parent_warrant: dict, child_scope: dict, issuer: str) -> dict:
    # Scope is transcribed from the parent, never reconstructed from agent context.
    parent_scope = parent_warrant["scope"]

    if not _is_subset(child_scope, parent_scope):
        raise ScopeLaunderingError(
            f"{issuer} attempted to widen scope: child={child_scope} "
            f"not subset of parent={parent_scope} (warrant {parent_warrant['id']})"
        )

    # Ceiling values propagate as min() down the chain.
    child_scope = dict(child_scope)
    child_scope["max_bytes"] = min(
        child_scope.get("max_bytes", parent_scope["max_bytes"]),
        parent_scope["max_bytes"],
    )
    child_scope["expires"] = min(
        child_scope.get("expires", parent_scope["expires"]),
        parent_scope["expires"],
    )

    return {
        "id": _new_warrant_id(),
        "issuer": issuer,
        "parent": parent_warrant["id"],
        "scope": child_scope,  # sealed; immutable after this point
        "signature": _sign(issuer, child_scope),
    }


def _is_subset(child: dict, parent: dict) -> bool:
    if child.get("resource") != parent.get("resource"):
        return False
    if not set(child.get("actions", [])).issubset(set(parent.get("actions", []))):
        return False
    if child.get("max_bytes", 0) > parent.get("max_bytes", 0):
        return False
    if child.get("expires", 0) > parent.get("expires", 0):
        return False
    return True
