Skip to content

Instantly share code, notes, and snippets.

@nthj
Created July 28, 2025 17:23
Show Gist options
  • Save nthj/8ba4c99777b89d727f376636278a9710 to your computer and use it in GitHub Desktop.
Save nthj/8ba4c99777b89d727f376636278a9710 to your computer and use it in GitHub Desktop.
Claude session wrapper that uses git directory as a session UUID
#!/usr/bin/env zsh
#
# Claude session wrapper that uses git directory as a session UUID
# and handles resume/new session logic
#
# Instructions
# - Name a file `claude` and place in your $PATH
# - chmod +x ./claude
# - Point to your claude install; see a few lines down
# - If you don't use git worktree (you should! especially with claude),
# you might want to add some logic to the uuid generation to include the git branch
# Get the underlying claude binary directly
#
# ATTENTION DEVELOPER: LIKELY YOU NEED TO CHANGE THIS TO YOUR CLAUDE INSTALL
#
claude="$HOME/.volta/bin/claude"
if [[ ! -x "$claude" ]]; then
echo "Error: Claude binary not found at $claude" >&2
exit 1
fi
# Get the git directory
gitdir=$(git rev-parse --git-dir 2>/dev/null)
if [[ -z "$gitdir" ]]; then
echo "Error: Not in a git repository" >&2
exit 1
fi
# Get absolute path of git directory
gitdir=$(cd "$gitdir" && pwd)
# Generate UUID based on git directory using SHA1 hash
uuid=$(echo -n "$gitdir" | shasum -a 1 | awk '{print substr($1, 1, 8) "-" substr($1, 9, 4) "-" substr($1, 13, 4) "-" substr($1, 17, 4) "-" substr($1, 21, 12)}')
# Try to resume session first by checking if it exists
# NOTE: If anyone knows of a way to exec into this immediately if it succeeds but still fallback to the follow-up exec when it fails,
# I'm very interested in removing the extra wait here
if $claude --resume "$uuid" --print 2>/dev/null >/dev/null; then
# Session exists, exec into it
exec $claude --resume "$uuid" --permission-mode plan "$@"
else
# Resume failed, start new session
exec $claude --session-id "$uuid" --permission-mode plan "$@"
fi
@jmpage
Copy link

jmpage commented Jul 29, 2025

This works for finding previous sessions, although it could be fragile if claude-code ever changes how it stores sessions. You can use it in place of $claude --resume ... on line 40, no output redirection required:

function claude_session_check() {
    local project
    local uuid
    project=$(echo "$1" | sed 's/\//-/g')
    uuid="$2"

    if [[ -e ~/.claude/projects/$project/$uuid.jsonl ]]; then
        return 0
    else
        return 1
    fi
}

You will also need to modify line 32 to cd to $gitdir/..

NOTE: claude code appears to store sessions based on the pwd in which the session is started, so this won't actually work if you have a session in /home/nthj/workspace/my-repo and you start claude with this script in /home/nthj/workspace/my-repo/src. You could change line 32 to just use the pwd, which would fix this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment