# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-validly-signed-delegation-chain-during-mcp-tool-invocation-the-depth-quorum-invalidation-boundary-in-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-validly-signed-delegation-chain-during-mcp-tool-invocation-the-depth-quorum-invalidation-boundary-in-a.warrant.json
# Markdown SHA-256:   8689f9d7ce2f23fa952176c5f96a7c0949db22ec4578480abbc617892963c342
# Code AST SHA-256:   63c77b8a9b1416e52fc737387cf1102ef34a74271fb695b0600c3d670d6110d3
# Verified Classes:   AncestryQuorumMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AncestryQuorumMismatch(RuntimeError):
    """Raised when a signed AAIF chain is crypto-valid but fails live ancestry-quorum reconciliation."""
    pass


def verify_chain_for_dispatch(chain, registry_snapshot, resume_generation, cached_ancestry):
    """
    Enforce the three-stage AAIF gate with a pre-dispatch ancestry fence.
    chain: list of hops [root, ..., leaf], each with .delegator_id, .scope,
           .signature, .header_minted_at, .revocation_epoch.
    registry_snapshot: live view of fork-commit log, taken at dispatch time.
    resume_generation: monotonic counter incremented on every checkpoint resume.
    cached_ancestry: the ancestry view persisted by the leaf at mint time.
    """
    # Stage 1: signature gate (per-hop)
    for hop in chain:
        if not hop.verify_signature():
            raise AncestryQuorumMismatch(f"signature invalid at hop {hop.delegator_id}")

    # Stage 2: attenuation gate (monotonic scope narrowing)
    for parent, child in zip(chain, chain[1:]):
        if not child.scope.is_subset_of(parent.scope):
            raise AncestryQuorumMismatch(
                f"scope escalation at {child.delegator_id} under {parent.delegator_id}"
            )

    # Stage 3: live ancestry-quorum gate — MUST precede any side-effecting tool call.
    # A resumed instance may not trust its cached ancestry; re-reconcile against the
    # fork-commit log with a read-your-writes barrier.
    leaf = chain[-1]
    live_ancestors = set(registry_snapshot.ancestors_of(leaf.delegator_id))
    presented_ancestors = {hop.delegator_id for hop in chain[:-1]}

    if presented_ancestors != live_ancestors:
        # Completeness quorum: the presented ancestor set must equal the live set.
        raise AncestryQuorumMismatch(
            f"ancestor set mismatch for {leaf.delegator_id}: "
            f"presented={sorted(presented_ancestors)} live={sorted(live_ancestors)}"
        )

    if resume_generation > 0:
        # Any ancestor forked after the cached header was minted invalidates the leaf.
        for ancestor in presented_ancestors:
            fork_epoch = registry_snapshot.fork_epoch_at(ancestor)
            if cached_ancestry.get(ancestor, {}).get("minted_at", 0) < fork_epoch:
                raise AncestryQuorumMismatch(
                    f"stale cached ancestry for {ancestor}: header minted before "
                    f"fork epoch {fork_epoch} (resume_generation={resume_generation})"
                )

    return True  # cleared for pre-dispatch; tool call may now proceed
