# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-when-a-scoped-capability-token-is-re-minted-across-a-consent-chain-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-authority-when-a-scoped-capability-token-is-re-minted-across-a-consent-chain-hop.warrant.json
# Markdown SHA-256:   4f77a9bf58fd0ed5f7774ef3de0716437d179baaba2986a273f0dccdfe7bb326
# Code AST SHA-256:   97eb5762b9524f38847210d18373f5a6c42e53b166af5bf2e9ac63ae67d9945f
# Verified Classes:   ScopeWideningError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScopeWideningError(RuntimeError):
    """Raised when a re-minted delegated token exceeds its parent's scope claim."""
    pass


def remint_delegated_token(parent_token: dict, intended_grant: str, child_id: str) -> dict:
    """
    Mint a child token from a parent token.

    INVARIANT: intersection is computed against parent_token["scope_claim"],
    never against any agent self-model or manifest. The token claim is the
    sole authoritative source of delegated authority.
    """
    parent_scope = parent_token["scope_claim"]          # immutable claim
    parent_depth = parent_token["max_depth"]

    if parent_depth <= 0:
        raise ScopeWideningError(
            f"cannot delegate from {parent_token['subject']}: max_depth exhausted"
        )

    # Subset check against the CLAIM, not the agent's runtime scope.
    if not _is_subset(intended_grant, parent_scope):
        raise ScopeWideningError(
            f"intended grant {intended_grant!r} is not within parent scope claim "
            f"{parent_scope!r} (subject={parent_token['subject']}); "
            f"re-mint from self-model would silently widen the consent chain"
        )

    return {
        "subject": child_id,
        "scope_claim": intended_grant,
        "max_depth": parent_depth - 1,
        "parent": parent_token["subject"],
        "parent_sig": parent_token["sig"],
    }


def _is_subset(child_scope: str, parent_scope: str) -> bool:
    # Simplified glob-prefix subset; real impl must handle action verbs + resource globs.
    c_action, c_res = child_scope.split(":", 1)
    p_action, p_res = parent_scope.split(":", 1)
    if c_action != p_action:
        return False
    c_prefix = c_res.rstrip("*")
    p_prefix = p_res.rstrip("*")
    return c_prefix.startswith(p_prefix)


def validate_chain(chain: list[dict]) -> None:
    """Re-check subset at every hop against the parent's embedded claim."""
    for parent, child in zip(chain, chain[1:]):
        if child["max_depth"] >= parent["max_depth"]:
            raise ScopeWideningError(
                f"depth not strictly decreasing: {parent['subject']} -> {child['subject']}"
            )
        if not _is_subset(child["scope_claim"], parent["scope_claim"]):
            raise ScopeWideningError(
                f"scope widened at hop {parent['subject']} -> {child['subject']}: "
                f"{child['scope_claim']!r} not within {parent['scope_claim']!r}"
            )
