Claude Code hooks for memory: load a brief, save notes, survive compaction

Use Claude Code hooks to add memory: load a brief at SessionStart, save notes at PreCompact and SessionEnd, re-inject after compaction. Scripts included.

The Esment Team

In short

  • Claude Code hooks are scripts the harness runs at lifecycle events. They are plumbing, not memory: you supply the store, and the hooks load it and write to it.
  • SessionStart and UserPromptSubmit can put text in Claude's context. PreCompact, PostCompact and SessionEnd cannot, so a save hook has to write to disk.
  • Injected text is capped at 10,000 characters per field, and SessionEnd gets 1.5 seconds by default. Keep the brief short and the save script fast.
  • A hand-built memory stays one folder, one machine and one tool. That is fine for a solo project and a poor fit once knowledge has to travel.

Claude Code hooks can give a session a memory, but only if you build the memory yourself. A hook is a script that Claude Code runs at a fixed point in its lifecycle. Point a SessionStart hook at a notes file and Claude begins each session with those notes in context. Point a PreCompact or SessionEnd hook at the same file and something gets written down before the session is gone.

This post is the memory-only slice of the hooks reference: which events matter, the exact fields they use, two scripts you can copy, and where the approach stops working. It is written against Anthropic's hooks reference and hooks guide, read in November 2026. Neither page carries a date, so check them if something here has changed.

Hooks are the plumbing, not the memory§

A hook does one thing: when an event fires, Claude Code runs your command and reads what it prints. Nothing in that loop decides what is worth remembering, stores it, or finds it again. Those jobs are yours.

So a hook-based memory has three parts: a place to keep notes (a file is enough), a hook that prints a brief from it at the start, and a way for new notes to reach it. The third part is the hard one, and we come back to it below.

If you want the concepts first, what fills Claude Code's context and what compaction drops covers them, and CLAUDE.md versus a memory server covers where each kind of knowledge belongs. This post is the wiring.

The Claude Code hook events that matter for memory§

The reference lists 33 events as of November 2026, covering tools, permissions, subagents, worktrees and more. Six matter for memory.

EventAdds context?Can block?Memory job
SessionStartYesNoLoad the brief
UserPromptSubmitYesYesRecall per prompt
StopCan continue the turnYesSave after each reply
PreCompactIts stdout steers the summaryYesSave before compaction
PostCompactNoNoStore the generated summary
SessionEndNoNoFinal save

Matchers narrow when a hook fires. SessionStart takes startup, resume, clear, compact or fork. PreCompact and PostCompact take manual or auto. SessionEnd takes clear, resume, logout, prompt_input_exit or other. UserPromptSubmit and Stop have no matcher and always fire.

Two details in that table decide the design. Only SessionStart and UserPromptSubmit put text in front of Claude, so loading happens there. And Stop is not the end of a session: it fires every time Claude finishes responding, and it does not run when you interrupt. For a once-per-session write, use SessionEnd.

SessionStarthookprints briefNotes fileread at startyour storeClaude'scontext

SessionStart hook → Notes file → Claude's context

The load half: a SessionStart hook reads your notes and prints them into context. The write half is a separate hook.

The settings.json shape and where it lives§

Hooks go in a settings file. The structure is three levels: an event, then a matcher group, then a list of handlers. A handler of type command runs a shell command.

json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|compact",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/memory-brief.sh" }
        ]
      }
    ],
    "PreCompact": [
      {
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/save-notes.sh" },
          { "type": "command", "command": "echo 'Keep the current task, decisions made and their reasons, and open questions.'" }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          { "type": "command", "timeout": 10, "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/save-notes.sh" }
        ]
      }
    ]
  }
}

Where the file lives sets who gets the hooks:

  • ~/.claude/settings.json applies to every project on your machine.
  • .claude/settings.json is shared with the project, so teammates get the hooks too.
  • .claude/settings.local.json is yours alone and is gitignored.

Run /hooks inside Claude Code to browse what is configured. CLAUDE_PROJECT_DIR is exported to command hooks, which is why the paths above start with it. A matcher made only of letters, digits, underscores, hyphens, spaces, commas and pipes is read as an exact string or a list, so startup|resume|compact means those three sources and nothing else. Omit the matcher and the hook runs for every source.

How text from a hook reaches Claude§

There are two routes, and both work on SessionStart and UserPromptSubmit.

  1. Plain stdout. With exit code 0, whatever the command prints is added to Claude's context.
  2. JSON with additionalContext. Print one JSON object with hookSpecificOutput.hookEventName and hookSpecificOutput.additionalContext. The text is wrapped as a system reminder. On SessionStart it sits at the start of the conversation, before your first prompt.

Choose one route per hook: use the exit code or the JSON, not both.

The docs also advise writing injected text as plain statements of fact. Imperative, system-style text ("you must", "ignore previous instructions") can trip prompt-injection defenses, and it is a bad habit for another reason covered in the safety section. Alex prefers pnpm works better than ALWAYS use pnpm.

Recipe: load a brief at session start§

The recipe uses a plain Markdown file, .claude/memory/notes.md, as the store. This script prints the newest part of it as additionalContext. It needs jq. Save it as .claude/hooks/memory-brief.sh and make it executable.

bash
#!/usr/bin/env bash
# Print the saved notes as SessionStart context. Needs jq.
NOTES="$CLAUDE_PROJECT_DIR/.claude/memory/notes.md"
[ -f "$NOTES" ] || exit 0

# Stay well under the 10,000-character cap: take the newest ~8,000 characters.
BRIEF=$(tail -c 8000 "$NOTES")

jq -n --arg ctx "Project notes saved from earlier sessions (facts, newest last):
$BRIEF" '{hookSpecificOutput: {hookEventName: "SessionStart", additionalContext: $ctx}}'

A notes file might read:

md
- Alex Rivera prefers pnpm over npm in this repo.
- The billing API moved to v2 on Nov 3; v1 calls in /legacy are being removed.
- Sam Okafor owns the release checklist. Priya Raman reviews anything under /payments.

We ran the script by hand against a file like this one, and it printed the JSON object the docs describe. We did not run it inside a live Claude Code session for this post, so test it in yours with a throwaway notes file before relying on it.

SessionStart has no decision control. It cannot block anything, and exit code 2 only shows stderr to you while the session carries on. It also runs again on resume and on a fork, because those are SessionStart sources too.

Recipe: save notes before compaction and at session end§

This is the half people skip, and it is the weaker half. A hook cannot read Claude's mind. What it can do is write down facts the harness hands it, and nudge the compaction summary toward what you care about.

PreCompact receives trigger (manual or auto) and transcript_path, the .jsonl file of the session so far. Its stdout is used as instructions for the compaction summary, which is what the echo in the settings above does. SessionEnd receives reason. Both also receive the common fields, including session_id. This script, .claude/hooks/save-notes.sh, logs a dated pointer for either event:

bash
#!/usr/bin/env bash
# Append a dated marker for PreCompact and SessionEnd. Needs jq.
INPUT=$(cat)
EVENT=$(jq -r '.hook_event_name' <<<"$INPUT")
WHY=$(jq -r '.trigger // .reason // "unknown"' <<<"$INPUT")
SESSION=$(jq -r '.session_id' <<<"$INPUT")
TRANSCRIPT=$(jq -r '.transcript_path' <<<"$INPUT")

mkdir -p "$CLAUDE_PROJECT_DIR/.claude/memory"
printf '%s | %s (%s) | session %s | transcript: %s\n' \
  "$(date +%Y-%m-%d)" "$EVENT" "$WHY" "$SESSION" "$TRANSCRIPT" \
  >> "$CLAUDE_PROJECT_DIR/.claude/memory/sessions.log"
exit 0

This writes a log of where each session's full transcript lives. It does not write a summary. That is deliberate. The script above is the raw-data step, and anything smarter belongs outside the hook.

Two limits apply here:

  • SessionEnd is short on time. The default overall budget is 1.5 seconds. A per-hook timeout raises the budget to match, up to 60 seconds, which is why the settings above set "timeout": 10. The CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS variable does the same job. Plugin-provided hook timeouts do not raise the budget.
  • PostCompact can store the summary. It receives compact_summary, the summary Claude generated, and has no decision control. If you want compaction summaries kept, a PostCompact hook that appends that field to a file is the documented place.

To get real notes into notes.md, the plain way works: ask Claude at the end of a task to append the decisions and their reasons to that file, as short factual lines. The hooks load them next time. That step depends on you asking, which is the honest cost of a do-it-yourself memory.

Recipe: keep your notes after compaction§

Compaction replaces the conversation with a summary, so details from earlier can be lost. The hooks guide's recipe for this is a SessionStart hook whose matcher is compact: after compaction, the hook prints what Claude must keep.

  1. Open .claude/settings.json (or your local or user settings file).
  2. Add a SessionStart entry with "matcher": "compact".
  3. Point its command at memory-brief.sh, or at a one-line echo for a short reminder.
  4. Run /hooks to confirm Claude Code sees it.
  5. Trigger /compact in a throwaway session and check that the notes are back in context.

The settings example earlier already covers this, since startup|resume|compact includes the compact source. The hooks guide treats short reminders this way, and suggests CLAUDE.md instead for context that should load in every session. Deciding what belongs in a session at all is the subject of context engineering. For a project's standing rules, that advice is right, and AGENTS.md and CLAUDE.md are the place for them. Hooks earn their keep for the parts that change: current task, recent decisions, what was tried.

Safety: hooks run with your permissions§

A command hook runs arbitrary shell with your permissions, and a project hook runs for everyone who opens the repo, so read .claude/settings.json in a repo you clone before you trust it. Project hooks follow the workspace trust rule. Managed settings can restrict hooks too: allowManagedHooksOnly blocks user, project, local and plugin hooks, and disableAllHooks turns them off.

Memory adds a second concern. Whatever your hook prints becomes text Claude reads, so the notes file is an input to the model. Three habits help:

  • Write facts, not commands, so a stray line cannot read as an instruction.
  • Keep secrets out of notes and out of transcripts you log. A file of tokens that loads on every start is a liability.
  • Read the file now and then. If a line is wrong, Claude acts on a wrong line with full confidence.

Hooks also have exit-code rules worth knowing when something misbehaves. Exit 0 means success and stdout is read. Exit 2 is a blocking error on events that can block, with stderr as the reason. Any other code, including 1, is a non-blocking error and the action proceeds. A script that fails with exit 1 does not stop anything, which makes it easy to miss. When a hook seems to do nothing, run it by hand with sample JSON on stdin, then check /hooks.

What a do-it-yourself memory can't do§

The recipe works for one developer, one repository and one machine. Its limits are structural rather than bugs.

A hook-built memory

Good at–Loading a short brief–Surviving /compact–Living in your repo–Costing nothingLeaves to you✓Deciding what to keep✓Pruning stale notes✓A 10,000-char ceiling✓Other tools and machines✓Teammates' own notesvs

Good at: Loading a short brief; Surviving /compact; Living in your repo; Costing nothing. Leaves to you: Deciding what to keep; Pruning stale notes; A 10,000-char ceiling; Other tools and machines; Teammates' own notes.

What the hook recipe covers, and what stays manual.
  • Nothing curates. The file grows until your tail cuts off the oldest lines. Old and wrong lines survive as long as the new ones do.
  • It reaches one tool. Cursor, ChatGPT and a second Claude Code machine do not see .claude/memory. For that problem, see how to share memory between Claude Code and Cursor.
  • It does not search. The brief is the newest slice, not the relevant slice. UserPromptSubmit can add context per prompt, but you write the lookup. How a real memory ranks results is in what each stage of our retrieval cascade is worth.
  • It depends on the harness. Hooks fire only when Claude Code does. A chat in the browser has none of them.

Claude Code's own auto memory covers part of this ground. See why Claude seems to forget between sessions for what it does and does not keep, and keeping memory on your own machine for the case for storing it locally.

Which setup to pick§

  • One repo, rules that rarely change: CLAUDE.md or AGENTS.md. No hooks needed.
  • Context that changes during a project and has to survive compaction: the SessionStart recipe above.
  • Knowledge that has to follow you across tools, machines or people: a shared memory, with hooks as an optional delivery route. The broader picture is in long-term memory for AI agents.

Start with the smallest version: one notes file and the SessionStart script. Add the save hooks once you have felt the first compaction hurt.

Questions, answered§

Can Claude Code hooks give it memory?

Not by themselves. Hooks are scripts the harness runs at lifecycle events. You supply the store, such as a Markdown file. A SessionStart hook prints it into context, and a PreCompact or SessionEnd hook writes to it. The injection half is documented. The saving logic is yours to write.

How does a SessionStart hook add context?

With exit code 0, plain stdout is added to Claude's context. Or print JSON with hookSpecificOutput.hookEventName set to "SessionStart" and an additionalContext string. It lands at the start of the conversation, before the first prompt. Each field is capped at 10,000 characters.

How do I re-inject context after compaction?

Add a SessionStart hook with the matcher "compact" and a command that prints what Claude must keep. Anthropic's hooks guide shows this with a one-line echo. Replace the echo with a script that reads your saved notes, as in the recipe above.

Does SessionEnd have enough time to write a summary?

By default its overall budget is 1.5 seconds. A per-hook timeout raises the budget to match, up to 60 seconds, and so does the CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS variable. Keep the hook quick: write raw data now and do any heavy summarizing elsewhere.

Does the Stop hook run at the end of a session?

No. Stop runs each time Claude finishes responding, not once per session, and it does not run when you interrupt. Check the stop_hook_active field to avoid loops. SessionEnd is the event that fires when a session ends.

Is it safe to inject stored notes into context?

Treat stored notes as untrusted input. Hooks run with your permissions, and text in context can steer Claude. Write facts, not commands, keep secrets out of the file, and read what the hook prints. The docs note that imperative, system-style text can trigger prompt-injection defenses.

Pass it on →

Keep reading

all posts →
Agents & context8 min

AGENTS.md vs CLAUDE.md: what it is, who reads it, and how to use both

AGENTS.md explained: what it is, which coding agents read it, how it differs from CLAUDE.md, how to keep one file, a copyable template, and why it isn't memory.

#AGENTS.md #CLAUDE.md
Agents & context7 min

Context engineering: what it is, where memory fits, and a practical checklist

Context engineering explained: where the term came from, the parts of a context, how it fails, where durable memory fits, and a checklist for ten minutes.

#contextengineering #AGENTS.md
Memory fixes8 min

Claude memory not working? A checklist for the apps and Claude Code

Claude memory not working? Check pause, incognito, Projects, plan and admin settings, then CLAUDE.md and auto memory in Claude Code, with the fix for each.

#Claude #ClaudeCode

a note for you

New posts, by email.

Fixes, guides and Lab notes on AI memory — about two a month. No product news, unsubscribe in one click.

Or follow the RSS feed