DEV Community

Vildanden
Vildanden

Posted on

Leave a session handoff when Claude Code exits, with a SessionEnd hook

A Claude Code session can end while the next person — or your future self — still has to reconstruct the branch, the dirty tree, and what was mid-flight. A SessionEnd hook runs when the session exits, so you can write a short local handoff without remembering to paste a recap.

Keep the hook local, fast, and free of network calls.

The hook

Save this as .claude/hooks/session_end_handoff.py and make it executable:

#!/usr/bin/env python3
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

try:
    json.load(sys.stdin)
except json.JSONDecodeError:
    pass

def git(*args: str) -> str:
    try:
        result = subprocess.run(
            ["git", *args],
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            timeout=4,
        )
        return result.stdout.strip() if result.returncode == 0 else ""
    except (OSError, subprocess.SubprocessError):
        return ""

branch = git("branch", "--show-current")
status = git("status", "--porcelain")
changed = [line for line in status.splitlines() if line.strip()]
now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")

lines = [
    f"# Session handoff — {now}",
    "",
    f"- Branch: {branch or 'unknown'}",
    f"- Changed paths: {len(changed)}",
]
if not branch and not changed:
    lines.append("- Note: not a git repo, or git was unavailable.")
elif changed:
    lines.append("")
    lines.extend(changed[:20])
    if len(changed) > 20:
        lines.append(f"... {len(changed) - 20} more")
lines.append("")
lines.append("This file is local session residue. Commit it only if your team wants the handoff in git.")

out = Path(".claude") / "handoff.md"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(lines) + "\n", encoding="utf-8")
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under SessionEnd with command set to python3 .claude/hooks/session_end_handoff.py.

Why this beats a pasted prompt

A recap in the transcript only helps if someone opens that session again. The hook writes a file in the repo workspace at exit, so the next session can start from branch and dirty paths instead of scrolling. If you do not want the handoff in git, add .claude/handoff.md to .gitignore or keep it beside settings.local.json.

Tips

  • Keep the hook local, fast, and free of network call..
  • Pair it with a SessionStart hook that injects git status, so the next session reads the tree at both ends.
  • If a worktree is not a git repo, the hook should still exit 0 and write a short "not a git repo" note rather than failing the shutdown.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (0)