# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-an-aaif-credential-s-sub-matches-but-its-act-claim-was-silently-collapsed-by-an-intermediat.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-an-aaif-credential-s-sub-matches-but-its-act-claim-was-silently-collapsed-by-an-intermediat.warrant.json
# Markdown SHA-256:   72b3aa738ef621dd9c9772f785c6080bf8d5bf81b7778f770a84658e1eb515c5
# Code AST SHA-256:   e4cf7a11943fb79cbbe7dbb92ea11b830448feddb39bdd40158c6506d6e90910
# Verified Classes:   DelegationChainCollapseError, ActEntry, Credential
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationChainCollapseError(RuntimeError):
    """Raised when a child credential's `act` claim is not a faithful
    one-element extension of its parent's `act` claim."""


@dataclass(frozen=True)
class ActEntry:
    sub: str
    iss: str


@dataclass(frozen=True)
class Credential:
    sub: str
    iss: str
    act: tuple[ActEntry, ...]
    credential_id: str
    signature_valid: bool


def mint_child(parent: Credential, issuer_sub: str, issuer_iss: str,
               child_sub: str, credential_id: str) -> Credential:
    """Mint a delegated credential. MUST append exactly one act entry."""
    if not parent.signature_valid:
        raise DelegationChainCollapseError(
            f"refusing to delegate from invalid parent {parent.credential_id}"
        )
    # The only correct construction: append, never replace.
    new_act = parent.act + (ActEntry(sub=issuer_sub, iss=issuer_iss),)
    if len(new_act) != len(parent.act) + 1:
        raise DelegationChainCollapseError(
            f"non-monotonic act construction: {len(parent.act)} -> {len(new_act)}"
        )
    return Credential(sub=child_sub, iss=issuer_iss, act=new_act,
                      credential_id=credential_id, signature_valid=True)


def verify_delegation(child: Credential, parent: Credential,
                      expected_sub: str) -> None:
    """Reconstruct the relational invariant. Fail closed on any mismatch."""
    if not child.signature_valid:
        raise DelegationChainCollapseError(
            f"child {child.credential_id}: signature invalid"
        )
    if child.sub != expected_sub:
        raise DelegationChainCollapseError(
            f"child {child.credential_id}: sub {child.sub!r} != {expected_sub!r}"
        )
    expected_act = parent.act + (ActEntry(sub=child.iss, iss=parent.iss),)
    if len(child.act) != len(expected_act):
        raise DelegationChainCollapseError(
            f"child {child.credential_id}: act length {len(child.act)} "
            f"!= expected {len(expected_act)} (collapse detected)"
        )
    for i, (got, want) in enumerate(zip(child.act, expected_act)):
        if got != want:
            raise DelegationChainCollapseError(
                f"child {child.credential_id}: act[{i}] {got!r} != {want!r}"
            )


def authorize_privileged_action(child: Credential,
                                parent: Credential | None,
                                log_act_hash: str | None,
                                expected_sub: str,
                                action_scope: str) -> bool:
    """Gate for scope-expanding actions. Chain-unverified => deny."""
    if parent is not None:
        verify_delegation(child, parent, expected_sub)
        return True
    if log_act_hash is not None:
        import hashlib, json
        actual = hashlib.sha256(
            json.dumps([{"sub": e.sub, "iss": e.iss} for e in child.act],
                       sort_keys=True).encode()
        ).hexdigest()
        if actual != log_act_hash:
            raise DelegationChainCollapseError(
                f"child {child.credential_id}: act hash {actual} "
                f"!= log {log_act_hash}"
            )
        return True
    # Neither parent nor log: cannot verify chain integrity.
    raise DelegationChainCollapseError(
        f"child {child.credential_id}: chain-unverified; "
        f"refusing scope-expanding action {action_scope!r}"
    )
