# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-capability-token-whose-scope-narrows-silently-at-the-second-hop-and-then-over-permits-at-the-third.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-aaif-capability-token-whose-scope-narrows-silently-at-the-second-hop-and-then-over-permits-at-the-third.warrant.json
# Markdown SHA-256:   fdb6b9cd07043ceca09aac4d3803d1320e5875d86895be78f72ce9b3922e754b
# Code AST SHA-256:   1912887d6a44da924866ee12f4da0a188fc3bfab16a52f59c7e56f0c32790bb5
# Verified Classes:   ScopeChainIntegrityError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ScopeChainIntegrityError(RuntimeError):
    """Raised when an AAIF capability token chain is incomplete or over-permissive."""
    pass


def verify_delegation_chain(chain, requested_action):
    """
    chain: ordered list of token dicts, root first, leaf last.
    Each: {"hash": str, "parent_hash": str|None, "scope": set[str]}
    Returns effective scope if valid; raises ScopeChainIntegrityError otherwise.
    """
    if not chain:
        raise ScopeChainIntegrityError("empty delegation chain")

    # 1. Structural continuity: no gaps, correct parent links.
    for i in range(1, len(chain)):
        if chain[i]["parent_hash"] != chain[i - 1]["hash"]:
            raise ScopeChainIntegrityError(
                f"chain gap at hop {i}: parent_hash={chain[i]['parent_hash']!r} "
                f"does not match ancestor hash={chain[i - 1]['hash']!r}"
            )

    # 2. Root must have no parent.
    if chain[0]["parent_hash"] is not None:
        raise ScopeChainIntegrityError("root token has non-null parent_hash")

    # 3. Effective scope = intersection of every ancestor scope.
    effective = set(chain[0]["scope"])
    for i, tok in enumerate(chain[1:], start=1):
        effective &= tok["scope"]
        # 4. Immediate-parent subset check (necessary, not sufficient alone).
        if not tok["scope"].issubset(chain[i - 1]["scope"]):
            raise ScopeChainIntegrityError(
                f"hop {i} scope {tok['scope']} not subset of "
                f"immediate parent scope {chain[i - 1]['scope']}"
            )

    # 5. Requested action must be in the intersected effective scope.
    if requested_action not in effective:
        raise ScopeChainIntegrityError(
            f"action {requested_action!r} not in effective scope {effective}; "
            f"leaf scope {chain[-1]['scope']} is insufficient"
        )

    return effective


def resume_from_checkpoint(persisted_chain, new_leaf):
    """
    Checkpoint resume must restore the FULL chain, not re-anchor to root.
    """
    if not persisted_chain or len(persisted_chain) < 2:
        raise ScopeChainIntegrityError(
            "checkpoint lacks intermediate chain; refusing to re-anchor to root"
        )
    last = persisted_chain[-1]
    if new_leaf["parent_hash"] != last["hash"]:
        raise ScopeChainIntegrityError(
            f"resumed leaf parent {new_leaf['parent_hash']!r} does not match "
            f"last persisted hop {last['hash']!r}; chain would skip attenuation"
        )
    return persisted_chain + [new_leaf]
