Skip to main content
MindStudio
Pricing
Blog About
My Workspace

Claude Code Hooks Explained: How Pre-Session and Post-Compaction Hooks Keep Your Agent on Track

Claude Code's 18+ hook types include pre-session injection and post-compaction hooks that reinsert agent identity after context compression.

MindStudio Team RSS
Claude Code Hooks Explained: How Pre-Session and Post-Compaction Hooks Keep Your Agent on Track

Your Claude Code Agent Forgets Who It Is — Here’s the Fix

Claude Code has 18+ hook event types, and most people use zero of them. Two of those hooks — the pre-session injection hook and the post-compaction hook — solve a problem that quietly degrades long agent sessions: your agent loses its identity mid-conversation, and you don’t notice until the output starts drifting.

This post is specifically about those two hook types, why they exist, and how to use them.


Why Your Agent Starts Strong and Ends Weird

Here’s what happens in a long Claude Code session.

You start with a well-crafted CLAUDE.md — your identity document, your rules, your context. The agent reads it at session start and behaves exactly as you’d expect. It knows your business, your constraints, your preferred output format.

Then the conversation gets long. Claude Code has a finite context window. When that window fills up, it runs a process called compaction — it summarizes the conversation history to make room for more. This is necessary and mostly works well. But here’s the catch: the compaction summary doesn’t always faithfully preserve everything in your CLAUDE.md. The core identity you injected at the start? It can get compressed into a vague summary or dropped entirely.

The result is an agent that started as your well-briefed assistant and gradually became a generic model that has forgotten your name, your rules, and your constraints. You’ll see it in subtle ways first — slightly different tone, slightly different output structure — and then in more obvious ways, like it stops following a formatting rule you care about.

This is the problem hooks solve.


What a Hook Actually Is

A hook in Claude Code is an event trigger. When something specific happens in the agent’s lifecycle, the hook fires and runs whatever you’ve configured it to run.

Mark Kashef, who builds agentic operating systems for businesses, describes it plainly: a hook is an event that will always fire at one of 18+ events that happen in Claude Code. Not “might fire.” Not “fires if the model remembers.” Always fires. That determinism is the whole point.

The 18+ events cover the full lifecycle of an agent session: session start, session end, before a tool call, after a tool call, before the model responds, after the model responds, and several more. Each event is a hook point where you can inject behavior that the model doesn’t control.

This is the key distinction. Hooks are not prompts. You can’t ask the model to “always remember to check X” and rely on that. The model might remember. It might not. A hook doesn’t ask — it runs.

If you’re building anything more complex than a single-session task, this matters a lot. The self-evolving Claude Code memory system built with Obsidian and hooks is a good example of hooks doing work that prompts simply can’t do reliably.


The Two Hooks That Matter Most for Identity

Of the 18+ hook events, two are particularly important for keeping your agent coherent across a long session.

Pre-Session Injection Hook

This hook fires at the start of every new session, before the agent does anything else.

What you put here gets injected into the context before the model sees any user input. The typical use case: inject your CLAUDE.md content, or a condensed version of it, so the agent starts every session with full context about who it is and what it’s supposed to do.

Why not just rely on CLAUDE.md being read automatically? Claude Code does read it — but the pre-session hook gives you control over how and when that context arrives, and lets you add dynamic content. If you use Obsidian for notes, for example, you can configure the pre-session hook to pull in files from a specific folder that are relevant to the current project. The agent starts each session not just with static rules but with fresh, relevant context.

Kashef gives a concrete example: if you’re working in a folder that contains litigation files or revenue data, the pre-session hook can pull those in alongside your CLAUDE.md content. The agent doesn’t have to go looking for them. They’re already there when the session opens.

Post-Compaction Hook

This is the one most people don’t know exists, and it’s arguably more important.

The post-compaction hook fires immediately after Claude Code runs its context compression. That’s the exact moment when your agent’s identity is most at risk of being lost. The hook fires, and you can use it to reinsert your core identity document.

VIBE-CODED APP
Tangled. Half-built. Brittle.
AN APP, MANAGED BY REMY
UIReact + Tailwind
APIValidated routes
DBPostgres + auth
DEPLOYProduction-ready
Architected. End to end.

Built like a system. Not vibe-coded.

Remy manages the project — every layer architected, not stitched together at the last second.

Think about what this means practically. Your agent can run for hours, compress its context multiple times, and each time it does, the post-compaction hook fires and puts your CLAUDE.md back in. The agent never drifts far from its original configuration because the identity gets re-anchored every time the context resets.

Kashef’s framing is useful here: if you have longer conversations with your agents and find that when the conversation compacts you lose core information and have to repeat yourself, the post-compaction hook is the fix. You inject the core information about you, your business, what you do, who you are — and you get a much richer conversation as a result.


How to Set These Up

The good news: you don’t have to write these hooks from scratch. Claude Code has a built-in sub-agent called the Claude Code guide that can generate hooks for you. You describe what you want — “inject my CLAUDE.md at session start” or “reinsert my identity document after compaction” — and it writes the hook configuration.

The hooks themselves are typically shell scripts or simple programs that output text to be injected into the context. They live in your Claude Code configuration alongside your skills and CLAUDE.md.

A minimal post-compaction hook might look like this: a script that reads your CLAUDE.md file and outputs its contents. Claude Code runs that script after every compaction event and prepends the output to the new context. That’s it. The model sees your identity document again and picks up where it should have been.

For more dynamic setups — like Kashef’s Obsidian integration — the hook script can be more sophisticated: check which project folder is active, pull relevant notes, format them for injection. But the core mechanism is the same.

One thing worth understanding: hooks are deterministic. They don’t ask the model to do something. They run code. This is the same principle behind using scripts for validation rather than asking the model to validate — if the code needs formatting, run a formatter; if the schema needs validation, actually validate the schema. Hooks follow the same logic. Don’t ask the model to remember its identity. Inject it.


Where Hooks Fit in the Larger Picture

Hooks are one layer in a stack that also includes skills, MCPs, and your CLAUDE.md. Understanding where they fit helps you avoid using them for the wrong things.

A skill is a reusable markdown process document — your agent’s instructions for how to do a specific type of work. A hook is infrastructure that runs regardless of what work the agent is doing. Skills are about capability; hooks are about reliability.

An MCP (Model Context Protocol) connector gives your agent access to live data from external systems. A hook doesn’t fetch data from external systems — it runs locally and injects context. If you need live Salesforce data, that’s an MCP. If you need your identity document re-injected after compaction, that’s a hook.

Plans first. Then code.

PROJECTYOUR APP
SCREENS12
DB TABLES6
BUILT BYREMY
1280 px · TYP.
yourapp.msagent.ai
A · UI · FRONT END

Remy writes the spec, manages the build, and ships the app.

The distinction matters because mixing these up leads to fragile setups. Kashef’s benchmark on MCP usage is instructive here: MCP servers use 35x more tokens than equivalent CLI tools on the same task, with reliability dropping as task complexity increases. That’s not an argument against MCPs — they’re the right tool for live data. But it is an argument for using the right tool for each job. Hooks are cheap, deterministic, and local. Use them for the things that should be deterministic.

This is also why the Claude Code agentic workflow patterns post is worth reading alongside this one — it covers the broader patterns that hooks slot into, including how to structure the ReAct loop so deterministic checks happen at the right points.


The Skill File Connection

There’s one more piece worth understanding: how hooks interact with skills.

Skills in Claude Code are markdown files with YAML front matter. The front matter describes the use case — the agent reads it first and only loads the full skill if it’s relevant. This progressive disclosure keeps context lean. You might have 38 skills (Kashef’s count in his own setup) without bloating every session with all of them.

Hooks can work alongside this system. A pre-session hook might inject your top-level identity document plus a summary of available skills. The agent then knows what it can do without having to load every skill file upfront. When it needs a specific skill, it loads the full markdown. When it doesn’t, the front matter summary is enough.

This is the architecture of a level-4 agentic system — what the four-levels framework describes as an agentic AI system with multiple skills, shared memory, and coordinated behavior. Hooks are part of the infrastructure that makes that coordination reliable rather than hopeful.

Platforms like MindStudio take a different approach to this orchestration problem — 200+ models, 1,000+ integrations, and a visual builder for chaining agents and workflows — which is worth knowing about if you want the coordination layer without writing the hook infrastructure yourself.


A Practical Starting Point

If you’re running Claude Code sessions that last more than 20-30 minutes, or that involve complex multi-step work, here’s a minimal setup worth trying:

  1. Write a condensed version of your CLAUDE.md — call it identity-core.md — that contains only the most essential context: who you are, what project this is, the top 3-5 rules that must always apply.

  2. Create a pre-session hook that reads identity-core.md and outputs its contents. Claude Code injects this before every session starts.

  3. Create a post-compaction hook that does the same thing. Every time the context compresses, your core identity gets reinserted.

  4. Test it by running a long session deliberately — give the agent a complex task that will require many tool calls and eventually trigger compaction. Check whether the output quality holds up through the compression event.

That’s the baseline. From there, you can make the hooks more dynamic: pull in project-specific context, inject recent memory files, add Obsidian notes. But the two-hook setup above solves the core problem.

If you want to go further with memory systems, the AI second brain built with Claude Code and Obsidian covers how to structure the files that hooks can pull from — the memory layer that makes injection actually useful rather than just repetitive.

Cursor
ChatGPT
Figma
Linear
GitHub
Vercel
Supabase
remy.msagent.ai

Seven tools to build an app. Or just Remy.

Editor, preview, AI agents, deploy — all in one tab. Nothing to install.

For teams building more complex agent infrastructure, tools like Remy offer a different angle on the same underlying problem of keeping AI systems grounded in precise, structured source documents — Remy treats annotated markdown specs as the source of truth and compiles them into full-stack TypeScript applications, which is a useful mental model for thinking about how structured documents (like a well-written CLAUDE.md) can drive reliable behavior downstream.


The Honest Limitation

Hooks solve the compaction problem, but they don’t solve everything.

If your CLAUDE.md is vague, injecting it repeatedly just means the agent repeatedly starts from a vague foundation. The quality of what you inject matters as much as the injection mechanism. Kashef’s /silver-platter skill — which audits your existing Claude Code setup, maps your data sources, and generates an HTML data map with pantry/prep table/plate sections plus a 30-day plan — is specifically designed to help you figure out what should be in your identity and context documents before you start injecting them everywhere.

Hooks are infrastructure. They make your setup reliable. But reliable delivery of bad context is still bad context.

The agents that work well in production have both: good hooks that ensure consistent injection, and good documents that are worth injecting. Getting the hooks right is the easier half.

Presented by MindStudio

No spam. Unsubscribe anytime.