# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-authorization-scope-amplification-when-a-verifiable-credential-s-capability-chain-is-re-minted-mid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-authorization-scope-amplification-when-a-verifiable-credential-s-capability-chain-is-re-minted-mid.warrant.json
# Markdown SHA-256:   32d43d186a6d3a86edfb7478544c8e732cb20bcddd51493eae58f1a885906575
# Code AST SHA-256:   46d6e4c5798a6ad3ee00ee6d39fb9c30413f444049a1e9ade90ed71431653d14
# Verified Classes:   ScopeAmplificationError, StaleParentReferenceError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ScopeAmplificationError(RuntimeError):
    """Raised when a derived credential's scope is not a subset of the
    cited parent credential's scope, evaluated at the parent's mint-time
    snapshot rather than the parent agent's current holdings."""
    pass


class StaleParentReferenceError(RuntimeError):
    """Raised when a child credential cites a parent DID rather than a
    specific, resolvable parent credential version."""
    pass


@dataclass(frozen=True)
class Credential:
    cred_id: str
    subject_did: str
    scope: FrozenSet[str]
    parent_cred_id: str | None          # pinned parent version, not a DID
    issuance_epoch: int


def mint_child(
    parent: Credential,
    child_did: str,
    requested_scope: FrozenSet[str],
    now: int,
    parent_is_current_head: bool = False,
) -> Credential:
    # Invariant 1: child must cite a pinned parent credential version.
    if parent.cred_id is None or parent_is_current_head:
        raise StaleParentReferenceError(
            f"cannot derive from DID-level head; pin parent cred_id={parent.cred_id!r}"
        )

    # Invariant 2: containment evaluated against the *cited* parent's
    # mint-time scope, never the parent agent's refreshed holdings.
    amplified = requested_scope - parent.scope
    if amplified:
        raise ScopeAmplificationError(
            f"child scope {sorted(amplified)} not contained in "
            f"parent {parent.cred_id} scope {sorted(parent.scope)}; "
            f"re-delegation from root required"
        )

    digest = hashlib.sha256(
        f"{parent.cred_id}|{child_did}|{sorted(requested_scope)}|{now}".encode()
    ).hexdigest()[:16]
    return Credential(
        cred_id=f"vc:{digest}",
        subject_did=child_did,
        scope=requested_scope,
        parent_cred_id=parent.cred_id,
        issuance_epoch=now,
    )


def verify_chain_closure(chain: list[Credential]) -> FrozenSet[str]:
    """Transitive scope = intersection of every hop root->leaf.
    A leaf presenting more than this intersection is amplified."""
    if not chain:
        raise ScopeAmplificationError("empty credential chain")
    closure = chain[0].scope
    for cred in chain[1:]:
        if cred.parent_cred_id != chain[chain.index(cred) - 1].cred_id:
            raise StaleParentReferenceError(
                f"broken parent linkage at {cred.cred_id}"
            )
        closure = closure & cred.scope
    return closure


# --- incident replay ---
orch = Credential("vc:orch-root", "did:aaif:orch",
                  frozenset({"read:repo", "write:branch", "dispatch:subagent"}),
                  None, 1000)
plan_orig = mint_child(orch, "did:aaif:plan",
                       frozenset({"read:repo", "dispatch:subagent"}), 1010)
# planner is refreshed out-of-band to broad scope, but its *delegation
# authority* remains plan_orig. Attempting to hand exec the broad scope:
plan_refreshed = Credential("vc:plan-refresh", "did:aaif:plan",
                            frozenset({"read:repo", "write:branch", "dispatch:subagent"}),
                            plan_orig.cred_id, 1500)
try:
    mint_child(plan_refreshed, "did:aaif:exec",
               frozenset({"read:repo", "write:branch", "dispatch:subagent"}), 1510)
except ScopeAmplificationError as e:
    print("contained:", e)  # contained: child scope ['dispatch:subagent', 'write:branch'] ...
