Trust & Control/The Hook System
Intermediate9 min

Session and Context Hooks

SessionStart, SessionEnd, and PreCompact give you control at the session boundary — injecting context before Claude starts, cleaning up after it finishes, and preserving critical state before compaction erases it.

Quick Reference

  • SessionStart: inject context, set env vars, log session begin
  • $CLAUDE_ENV_FILE: variables written here in SessionStart persist across all Bash calls in the session
  • SessionEnd: write summary, update task tracker, log duration
  • PreCompact: save critical context before compaction discards fine detail
  • PostCompact: restore context, log that compaction occurred
  • InstructionsLoaded: fires when CLAUDE.md loads — validate or log configuration
  • CwdChanged: fires when working directory changes — load directory-specific env
  • FileChanged: fires when file is modified externally — trigger watchers or validation

The Session Lifecycle

Every Claude Code session has a beginning, middle, and end. SessionStart fires at the beginning, before Claude processes its first prompt. SessionEnd fires when the session closes. In between, PreCompact fires when context compaction is about to run — discarding fine-grained history to make room for new context.

These boundary events give you hooks that run exactly once per session rather than once per tool call. They're the right place for setup, teardown, and state preservation — not for per-action logic.