# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-agent-identity-has-silently-outlived-its-attestation-chain-during-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-verifiable-agent-identity-has-silently-outlived-its-attestation-chain-during-cross-org-federation.warrant.json
# Markdown SHA-256:   09ed50795bac40f578ab0c67731e66b381b8ea782b13e33f0c3e0122687396b8
# Code AST SHA-256:   6a06e6f94de51cd9fdad4b431c5c9f5ccec10a1f96b90921a43eab8c059ce284
# Verified Classes:   StaleAttestationChainError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleAttestationChainError(RuntimeError):
    """Raised when a presented agent credential verifies cryptographically but
    its attestation chain does not terminate at a currently-published trust
    anchor, or an intermediate in the chain is revoked."""
    pass


def derive_current_authority(
    agent_did: str,
    action: str,
    now: float,
    presented_chain: list,
    published_anchors: set,
    revoked_intermediates: set,
    propagation_bound: float,
) -> bool:
    # Walk from leaf up to root, checking each link is unrevoked and that the
    # chain actually terminates at a currently-published anchor.
    if not presented_chain:
        raise StaleAttestationChainError(
            f"empty attestation chain for {agent_did}"
        )

    for link in presented_chain:
        if link.issuer_did in revoked_intermediates:
            raise StaleAttestationChainError(
                f"intermediate {link.issuer_did} revoked in chain for {agent_did}"
            )
        if link.valid_until < now:
            raise StaleAttestationChainError(
                f"link {link.issuer_did} expired at {link.valid_until}, now {now}"
            )

    root = presented_chain[-1].issuer_did
    if root not in published_anchors:
        # The critical check: the chain is internally consistent but does not
        # reach a live anchor. This is the silent-failure boundary.
        raise StaleAttestationChainError(
            f"chain for {agent_did} terminates at {root}, "
            f"not a currently-published anchor"
        )

    # Authority must be re-derived here, not inherited from identity validation.
    derived_capabilities = _resolve_capabilities(presented_chain)
    if action not in derived_capabilities:
        return False

    # Enforce that the caller's cache freshness honored the propagation bound.
    if now - presented_chain[0].resolved_at > propagation_bound:
        raise StaleAttestationChainError(
            f"authority for {agent_did} resolved {now - presented_chain[0].resolved_at}s ago, "
            f"exceeds propagation bound {propagation_bound}s"
        )

    return True
