# Add a bounded project context hook to Claude Code session start

> Install a small project SessionStart hook that adds the current Git branch to Claude Code context. Check its direct output, startup and resume, and failure behavior.

By BIG CHANGE Editorial

Published: 2026-10-20T00:22:54.831Z
Updated: 2026-10-20T00:22:54.831Z
Canonical: https://bigchange.ai/blog/claude-code-session-start-branch-context-hook-guide

![Conceptual charcoal illustration of an unbranded desktop monitor with one short orange stroke above two soft charcoal strokes; a keyboard rests in front.](https://bigchange.ai/api/media/file/claude-code-session-start-context-hero-v2.png)
AI-generated conceptual illustration by BIG CHANGE; no actual Claude Code interface, hook execution or model result is depicted.

A Claude Code hook is a command the app runs at a named point in a session. This guide adds one project-scoped `SessionStart` hook that reads the current Git branch and supplies a short line of context when you start or resume a conversation. It follows [Anthropic's current hook reference](https://code.claude.com/docs/en/hooks), checked October 19, 2026. BIG CHANGE checked the script directly with Node and checked the settings JSON; we did not run a Claude Code hook or test a model response.

## The big change

- **What changed:** This project `SessionStart` hook supplies a short Git branch line when Claude Code starts or resumes a conversation.
- **Why it matters:** The current branch reaches session context at startup or resume without a manual paste each time.
- **What to watch:** Context does not enforce a rule or guarantee a model answer. Check actual startup and resume delivery in your own trusted project.

## Before you install it

Use a Git project you are authorized to change. You need Claude Code, Node.js and Git available in the same terminal, plus permission to edit the project's `.claude/settings.json`. Check `node --version`, `git --version` and `claude --version`. The preparation host had Claude Code 2.1.301 and Node 24.19.0; those observed versions are not minimum requirements.

**Review the branch name before sending it to a model.** A branch can contain a client, ticket or incident name. Filtering characters and shortening the string do not remove that meaning. Install this example only when your branch name is approved for model context. Otherwise change the script to emit an approved non-sensitive status and review that change before installation. [Anthropic's data-usage documentation](https://code.claude.com/docs/en/data-usage) explains the service's data handling; apply your own project permissions as well.

Hook commands run with your user permissions. Inspect existing project and user hooks, organization policy, and the complete script before enabling them. Project settings may be committed; `.claude/settings.local.json` stays local. This example uses the project settings file so the configuration is scoped to that project.

## Install the two files

1. Create `.claude/hooks/` inside the project. Save this entire block as `.claude/hooks/session-context.cjs`:

```javascript
'use strict';

const { execFileSync } = require('node:child_process');

const project = process.env.CLAUDE_PROJECT_DIR;
if (!project) {
  process.stderr.write('CLAUDE_PROJECT_DIR is unavailable\n');
  process.exit(1);
}

try {
  const raw = execFileSync('git', ['-C', project, 'branch', '--show-current'], {
    encoding: 'utf8',
    timeout: 1500,
    maxBuffer: 4096,
    stdio: ['ignore', 'pipe', 'pipe'],
  }).trim();
  const branch = raw ? raw.replace(/[^A-Za-z0-9._/-]/g, '_').slice(0, 80) : 'detached HEAD';
  process.stdout.write(`Current project branch: ${branch}\n`);
} catch {
  process.stderr.write('Could not read the project branch; check Git and project path\n');
  process.exit(1);
}
```

The Git child process has a 1.5-second timeout and a 4,096-byte output buffer. An empty branch result, as on detached HEAD, becomes `detached HEAD`. A missing project path or Git failure produces a short stderr diagnostic and exit code 1.

2. Open your existing `.claude/settings.json`. Merge the `hooks.SessionStart` entry below with the other settings and hook groups; preserve existing entries. The block shows the complete `settings.example.json` from the reviewed packet. If your file already has `SessionStart` entries, add this group to its array rather than replacing the array.

```json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/session-context.cjs"],
            "timeout": 5
          }
        ]
      }
    ]
  }
}
```

The matcher covers a new session and a resumed session. Anthropic also documents `clear`, `compact` and `fork` as `SessionStart` sources; this example deliberately omits them. The `args` field selects exec form: Claude Code invokes `node` with the resolved project script path as one argument, without shell quoting or parsing. On Windows, `node.exe` must resolve as an executable; a `.cmd` shim is unsuitable for exec form. The command's five-second hook timeout is separate from the script's 1.5-second Git timeout.

## Check the script, then check Claude Code

3. Before opening Claude Code, run the script in the project terminal and compare its output with Git. In PowerShell:

```powershell
$env:CLAUDE_PROJECT_DIR = (Get-Location).Path
node .claude/hooks/session-context.cjs
git branch --show-current
```

In Bash:

```bash
CLAUDE_PROJECT_DIR="$PWD" node .claude/hooks/session-context.cjs
git branch --show-current
```

Expect exactly one script stdout line, `Current project branch: BRANCH`, where `BRANCH` is the Git result after the script's character filter and 80-character limit. Detached HEAD prints `Current project branch: detached HEAD`. The direct check establishes only that the local script works in this terminal. In our preparation check, its ordinary branch result matched Git; missing and invalid project paths produced empty stdout, a diagnostic on stderr and exit 1. We inspected the long-name bound and detached-HEAD fallback in source but did not run those cases.

4. Start a fresh **interactive** Claude Code process in the trusted project with `claude --debug-file STARTUP_PRIVATE_LOG`, using a private path you control. Review the project and user hooks before accepting workspace trust. Inspect the debug log for a `SessionStart` event with source `startup`, the selected script path, its exit status and output handling. Ask Claude what branch context it received without letting it use a tool or read Git independently. Compare the answer and debug record with the direct result. Hook stdout enters Claude's context; it is not promised as a message in the visible UI.
5. Exit that session. Resume it in a separate process with `claude --debug-file RESUME_PRIVATE_LOG --resume`, then check the `SessionStart` `resume` event and repeat the prompt check without a tool or Git reread. Keep both debug logs private; they can expose project details. A non-interactive `-p` or SDK run does not give the same workspace-trust prompt and can run repository hooks automatically, so use the interactive flow for this check. Anthropic says edits to hook settings are normally picked up by its file watcher, but a fresh process gives a clearer startup and resume test.

If normal project work later changes the branch, repeat the direct check and a fresh session to see whether the line changes. Do not change branches solely to claim this guide was tested.

## If it does not run

Start with the direct script result, then check the JSON merge, `SessionStart` spelling, `startup|resume` matcher, project-root path, availability of `node` and `git`, workspace trust and debug errors. Missing `CLAUDE_PROJECT_DIR` prints `CLAUDE_PROJECT_DIR is unavailable` to stderr. A bad project path or Git failure prints `Could not read the project branch; check Git and project path`. Both exit 1 and print no context line. A `SessionStart` failure is diagnostic and nonblocking; it cannot serve as an action gate. Anthropic documents `PreToolUse` for controlling a tool action, which is a different event and requires its own reviewed design.

The script only runs local Git and makes no network request or model call. Claude Code startup, resume and prompt checks can consume your account, provider or model allowance; [Anthropic's costs guide](https://code.claude.com/docs/en/costs) has current terms. This guide assigns no fixed price and reports no paid session test.

For a separate task after a conversation is underway, our [guide to inspecting context and continuing a Claude Code session](https://bigchange.ai/blog/claude-code-session-context-continue-guide) covers context inspection and continuation. It does not configure this startup hook.

## Sources & further reading

- [Anthropic, Claude Code hooks reference](https://code.claude.com/docs/en/hooks) — Current primary specification checked October 19, 2026. Documents `SessionStart` sources and matchers, exec-form `args`, path placeholders, stdout context, settings reload, trust, debug logs and nonblocking failure behavior. This is documentation, not a BIG CHANGE hook execution.
- [Anthropic, Automate actions with hooks](https://code.claude.com/docs/en/hooks-guide) — Official walkthrough for hook setup and testing. The exact script and settings above are a bounded BIG CHANGE example reviewed for this guide; they are not a copied vendor test result.
- [Anthropic, Claude Code setup](https://code.claude.com/docs/en/setup) — Installation and environment requirements. Check current platform instructions before using the example.
- [Anthropic, Claude Code data usage](https://code.claude.com/docs/en/data-usage) — Current provider data-handling terms to review before sending branch information into model context; your project authorization remains a separate decision.
- [Anthropic, Manage costs effectively](https://code.claude.com/docs/en/costs) — Current account and usage guidance for the interactive checks. The local Git script itself makes no model or network request.

## Sources

- [Claude Code hooks reference](https://code.claude.com/docs/en/hooks) — Primary, current Anthropic manual checked against the approved 19 October 2026 snapshot and again during drafting. Establishes SessionStart startup/resume sources and matcher semantics, exec-form command and args, project-root placeholder, plain stdout context, settings watcher, workspace trust, debug-file inspection, Windows real-executable rule and nonblocking SessionStart errors. It describes product behavior; BIG CHANGE did not execute a Claude-invoked hook. No fixed manual revision date was stated.
- [Automate actions with hooks](https://code.claude.com/docs/en/hooks-guide) — Official Anthropic setup and testing walkthrough. It supports the reader's hook configuration and diagnostic process, not a claim that BIG CHANGE ran the sample inside Claude Code. The article's exact bounded Node script and settings came from the separately reviewed local implementation packet.
- [Claude Code advanced setup](https://code.claude.com/docs/en/setup) — Official installation and environment reference for checking local Claude Code setup. Preparation observed version 2.1.301 only; this source does not turn that observed version into a minimum requirement.
- [Claude Code data usage](https://code.claude.com/docs/en/data-usage) — Official account-dependent data-handling terms. The article directs readers to review them before putting Git branch information into model context; filtering and truncation do not prevent a branch name from revealing confidential client or incident details. No blanket privacy guarantee is inferred.
- [Manage costs effectively](https://code.claude.com/docs/en/costs) — Official account and model usage guidance for interactive startup/resume prompt checks. The local script itself makes no model or network request, while actual Claude sessions can consume plan, provider or API allowance. No fixed price or paid test is asserted.
- [How to inspect context and continue a Claude Code session](https://bigchange.ai/blog/claude-code-session-context-continue-guide) — Prior BIG CHANGE article 414, used for a contextual internal link and relationship classification only. It covers inspecting an existing conversation and continuing its task; it is not evidence for this hook's implementation or a direct dated parent.
