How to execute a cleanup command on tmux server/session exit?

For now, there is no specific way to have tmux automatically run commands triggered by detach or closing all windows in the session. However, since you already have a wrapper script (I will call this tmux_wrapper) that opens your desired custom-session, you can easily convert this script to automate cleanup. I do something very similar to this myself here, where I wanted to allow nested tmux sessions if I am attaching through ssh.

Since you have a custom experience in mind, you no longer need the tmux attach .... or similar commands, so I will assume you always start session for project A by something like tmux_wrapper A. In your wrapper you probably have a line similar to tmux new-session -s A. Here we can take advantage of the session name A. Then, at the end of your wrapper you can have a cleanup switch that only activates if the session is no longer live (i.e. windows/panes are no longer attachable).

A simple example tmux_wrapper would look something like this:

#!/bin/sh

sess=$1

# test if the session has windows
is_closed(){ 
    n=$(tmux ls 2> /dev/null | grep "^$sess" | wc -l)
    [[ $n -eq 0 ]]
}

# either create it or attach to it
if is_closed ; then
  tmux new -s $sess
else
  tmux attach -t $sess
fi

# the session is now either closed or detatched
if is_closed ; then
    # perform cleanup here ...
fi

Run it like tmux_wrapper A. Now, the cleanup will automatically occur for session A if and only if the session has been completely closed.