Guide
Claude Code hooks: a real-world example that tracks your sessions
Claude Code hooks run your own commands when something happens in a session: a prompt is sent, a tool runs, Claude stops. They are how Claude Gains knows how hard Claude worked today. This guide walks through the setup it uses, so you can build your own hook that observes a session without ever getting in its way.
1. Register the hook in settings.json
Hooks live under a hooks key in ~/.claude/settings.json (all projects) or a repo's .claude/settings.json (one project). Each event maps to matchers, and each matcher to commands. Two fields matter for an observer: async, so Claude Code does not wait for the command, and a short timeout in seconds.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "node ~/.claude-gains/app/dist/hook.js",
"timeout": 5,
"async": true
}
]
}
]
}
}When you install hooks from a script, merge into the existing file instead of overwriting it, write a backup first, and tag your entries (Claude Gains matches on its script path) so an uninstall removes only yours.
2. Pick the events you need
Claude Gains listens to seven events. Each one answers a different question about the session:
| Event | What Claude Gains does with it |
|---|---|
| SessionStart | A session opened. Claude Gains marks it live and notes the project folder. |
| UserPromptSubmit | You sent a prompt. Marks the session busy. Only the prompt's length is kept, never the text. |
| PostToolUse | A tool finished. Counts the call and its payload size, and keeps the session marked busy. |
| Stop | Claude finished its turn. The natural break: tokens are read and a drop may land. |
| SubagentStart | A subagent started. Counts as work in progress, so no workout interrupts it. |
| SubagentStop | A subagent finished. Its transcript is read for tokens too. |
| SessionEnd | The session closed. Final token read, session marked done. |
3. Keep the hook fast and harmless
A hook receives the event as JSON on stdin. An observer should do as little as possible: strip anything sensitive, hand the event to something long-running, and exit. No stdout (on some events Claude reads it), no exceptions, exit code 0.
// Read the event from stdin, keep only what you need, send it on.
let input = "";
for await (const chunk of process.stdin) input += chunk;
const event = JSON.parse(input);
// Never keep prompt text or tool payloads: sizes are enough.
if (typeof event.prompt === "string") event.prompt_length = event.prompt.length;
delete event.prompt;
delete event.tool_input;
delete event.tool_response;
try {
await fetch("http://127.0.0.1:7413/events", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(event),
signal: AbortSignal.timeout(300), // give up fast
});
} catch {
// Daemon down: append to a spool file and replay later.
}
// No stdout, always exit 0: a hook must never change what Claude does.The heavy lifting happens in a local daemon on port 7413, not in the hook. If the daemon is down, events go to a spool file that it replays on its next start, so nothing is lost and Claude never notices.
4. Get token usage from the transcript
Hook payloads include transcript_path but no token counts. The transcript is a JSONL file where each assistant message records its usage. On Stop, SubagentStop and SessionEnd, read it from the byte offset you saved last time (subagent transcripts sit in a subagents/ folder next to it, named after the session), and upsert usage by API message id so streamed duplicates and re-reads never double count. Claude Gains leaves out cache reads, which would otherwise make long sessions look far heavier than they are.
5. Act only at natural breaks
UserPromptSubmit, PostToolUse and SubagentStart mark a session busy; Stop and SessionEnd mark it idle. Claude Gains only drops a workout right after a Stop, or once every session has been idle for two minutes, so a notification never lands while Claude is still working. The same rule suits anything a hook triggers that needs your attention.
Try it without writing any code
Claude Gains installs all seven hooks, the daemon and a menu bar app in one command, and removes them with claude-gains uninstall.
npx claude-gains init