Claude Code hooks

Claude Code PreCompact hook: what it can and cannot do

A PreCompact hook runs right before Claude Code compacts a conversation. It can stop the compaction, or add instructions to the summary that compaction writes.

This page covers when the hook fires, what it can and cannot do, and a hook that keeps an open task through compaction. Every statement about Claude Code comes from the official hooks reference and guide, linked at the end.

When the hook runs

PreCompact runs before Claude Code is about to run a compact operation. The matcher says whether compaction was triggered manually or automatically:

manual
/compact.
auto
Auto-compact when the conversation reaches the auto-compact window, and idle compaction.

A matcher of manual or auto narrows the hook to one trigger. Without a matcher, it fires for both.

What arrives on stdin

Next to the common input fields, a PreCompact hook receives trigger and custom_instructions:

trigger
manual or auto.
custom_instructions
For manual, what the user passes into /compact. It is null when they pass nothing. For auto, it is always null.

What it can do

Steer the summary

When a PreCompact hook exits 0 and does not block, Claude Code uses its stdout as instructions for the compaction summary. Keep that stdout under 10,000 characters per hook. Claude Code cuts longer output at the cap and appends a marker.

Block compaction

Exit with code 2 to block compaction. For a manual /compact, the stderr message is shown to the user. You can also block by returning JSON with "decision": "block".

Blocking automatic compaction has different effects by timing:

  • Compaction triggered proactively, before the context limit: Claude Code skips it and the conversation continues uncompacted.
  • Compaction triggered to recover from a context-limit error the API already returned: the underlying error surfaces and the current request fails.

What it cannot do

  • Claude Code discards a PreCompact hook's systemMessage and continue fields.
  • It cannot put text into the conversation after compaction. For that, use a SessionStart hook with the compact matcher. The SessionStart page shows it.

To react to the new, compacted state, for example to log the generated summary, the reference offers a separate event: PostCompact. It runs after Claude Code completes a compact operation.

Example: keep context through compaction

Two hooks work together. PreCompact asks the summary to keep your open task. SessionStart with the compact matcher puts critical context back afterwards. A test in our repository runs the PreCompact script below.

1. Write the open task into a file

.claude/current-task.md holds a few lines: what you are doing and what is still open.

2. Add the PreCompact hook

.claude/hooks/keep-task.mjs
import { readFileSync } from "node:fs";
import { join } from "node:path";

const input = JSON.parse(readFileSync(0, "utf8"));

try {
  const file = join(input.cwd, ".claude", "current-task.md");
  const task = readFileSync(file, "utf8").trim().slice(0, 2000);
  if (task) {
    console.log(
      "Compaction trigger: " + input.trigger + ". " +
        "Keep this open task in the summary, word for word:\n" + task,
    );
  }
} catch {
  // No task file: print nothing and exit 0. Compaction runs as usual.
}

Without the file, the hook prints nothing and exits 0, and compaction runs as usual. With it, the stdout becomes an instruction for the summary.

3. Register it

.claude/settings.json
{
  "hooks": {
    "PreCompact": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/keep-task.mjs"
            ],
            "timeout": 10
          }
        ]
      }
    ]
  }
}

4. Put context back after compaction

A SessionStart hook with the compact matcher adds the text of your command to Claude's context after every compaction. This is the guide's own example:

.claude/settings.json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Reminder: use Bun, not npm. Run bun test before committing. Current sprint: auth refactor.'"
          }
        ]
      }
    ]
  }
}

You can replace the echo with any command that produces dynamic output, such as git log --oneline -5.

What cachly does

The cachly plugin does not install a PreCompact hook. It ships three hooks: SessionStart, UserPromptSubmit and Stop.

Its SessionStart hook has no matcher. By the matcher rules in the reference, that means it fires on every start type, including compact, with a timeout of 30 seconds.

Claude Code
/plugin marketplace add cachly-dev/cachly-mcp
/plugin install cachly-brain@cachly

Then turn on auto-update once: /plugin → Marketplaces → cachly → Enable auto-update. Claude Code leaves it off for marketplaces outside Anthropic's own, and the hooks update only with the plugin.

What compaction keeps and what it only summarizes: Lost context after /compact. More on the other events: SessionStart hook, Stop hook and UserPromptSubmit hook.

Sources

Checked against the hooks reference on .

More: All Claude Code hook events · AI memory in three layers · MCP integration · All docs