Skip to content

SessionStart hook returns exit(1) on resume when stale PID file exists #134

@yulflow

Description

@yulflow

Description

When resuming a Claude Code session, mgrep_watch.py checks for an existing PID file and exits with code 1 if found. This causes Claude Code to display "SessionStart:startup hook error" on every resume.

Root Cause

In hooks/mgrep_watch.py:

pid_file = f"/tmp/mgrep-watch-pid-{payload.get('session_id')}.txt"
if os.path.exists(pid_file):
    debug_log(f"PID file already exists: {pid_file}")
    sys.exit(1)  # ← This shows as "error" in Claude Code

When a session ends abnormally (Ctrl+C, crash, etc.), mgrep_watch_kill.py (SessionEnd hook) doesn't run, leaving stale PID files in /tmp/. On next resume with the same session_id, the PID file check triggers exit(1).

Related

Suggested Fix

Instead of blindly exiting on PID file existence, check if the process is actually alive:

pid_file = f"/tmp/mgrep-watch-pid-{payload.get('session_id')}.txt"
if os.path.exists(pid_file):
    try:
        old_pid = int(open(pid_file).read().strip())
        os.kill(old_pid, 0)  # Signal 0 = existence check only
        # Process is alive — skip duplicate, exit cleanly
        debug_log(f"mgrep watch already running (pid={old_pid}), skipping")
        sys.exit(0)  # exit(0), not exit(1)
    except (ProcessLookupError, ValueError, OSError):
        # Process is dead — remove stale PID file and continue
        debug_log(f"Stale PID file removed: {pid_file}")
        os.remove(pid_file)

This way:

  • If process is alive → exit(0) (no error message, just skip)
  • If process is dead → clean up PID file and start fresh

Environment

  • OS: macOS (Darwin 25.2.0, Apple Silicon)
  • Claude Code version: latest
  • mgrep version: 0.0.0 (plugin cache)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions