Claude Code PreCompact Hook: Save Task State Before Compaction and Re-Inject It After

Set up a Claude Code PreCompact hook that saves task state to a file, then re-inject a capped summary after compaction with a SessionStart compact hook.

Claude Code PreCompact hook hero: a long session of message bars feeds a compaction funnel that outputs a short summary, while a PreCompact arrow saves progress.md and a SessionStart compact arrow restores a capped block with the task, next step and migrations rule.Claude Code PreCompact hook hero: a long session of message bars feeds a compaction funnel that outputs a short summary, while a PreCompact arrow saves progress.md and a SessionStart compact arrow restores a capped block with the task, next step and migrations rule.
Illustrative case task:billing-refactor-01. The PreCompact hook saves state to progress.md before compaction; the SessionStart compact hook restores a capped block afterward. Events from Anthropic's Claude Code hooks guide.

You are three hours into a refactor. Claude Code has pulled a tax function out of an invoice module, written tests for it and switched one import. Then the context window fills, auto-compaction runs, and the next turn proposes a schema tweak under migrations/, the one directory you said to leave alone. That instruction lived early in the conversation, and compaction summarized it away.

This tutorial fixes that with a Claude Code PreCompact hook that writes a small state file just before compaction, paired with a SessionStart hook matched to the compact source that reads the file back into context right after. You finish with two short bash scripts, one settings block, a worked case called task:billing-refactor-01, and checks that show whether the restored block arrived and how large it is.

The prompt for writing this up was shrey’s Nov. 25 X article, “The Trick I Use So Compaction Never Touches My Agent”, which points readers at Anthropic’s hooks and context-window documentation and at OpenCode’s compaction page. The same day Anthropic published Claude Code v2.1.332, whose notes include fixes for compaction failing when a summary kept running past the output limit, and for turns ending in “Prompt is too long” after repeated auto-compaction failures. Nothing below depends on that release. Every event, matcher and output rule used here comes from Anthropic’s current hooks guide.

GitHub release page for anthropics/claude-code v2.1.332.
GitHub release page for Claude Code v2.1.332, released Nov. 25, 2026; its notes include compaction and hook-output fixes. Source: GitHub, anthropics/claude-code. · Original source

Before you start. You need Claude Code installed, a git repository you can edit, and a shell that runs bash: macOS, Linux, WSL, or Git Bash on Windows. Install jq for JSON parsing; the hooks guide suggests brew install jq on macOS and apt-get install jq on Debian and Ubuntu. You should be comfortable editing JSON by hand, because one trailing comma in a settings file stops every hook in that file from loading.

What compaction keeps, and what it drops

Anthropic’s context window page lists what survives a compaction. The rows that matter for this guide:

Mechanism After compaction
System prompt and output style Both still apply
Project-root CLAUDE.md and unscoped rules Re-injected from disk
The plan Claude wrote in plan mode Re-injected from disk
Rules with paths: frontmatter, nested CLAUDE.md files Reloaded on demand when Claude touches their trigger file; earlier copies are summarized away
Files Claude read or edited Up to five re-read, most recently modified first; a file over 5,000 tokens comes back as a path reference
Context that hooks added earlier Summarized with the rest of the conversation
SessionStart hooks that match the compact source Run, and their output is added to the compacted context

Three of those rows drive the design. First, the conversation itself becomes a summary. How Claude Code works says that summary keeps your requests and key code snippets, but detailed instructions from early in the conversation may be lost. Second, anything a hook injected earlier, for example at startup, is summarized like any other text, so a one-time injection does not protect you through the next compaction. Third, a SessionStart hook with the compact matcher runs after every compaction, and its output lands in the fresh context. That last row is the re-injection point this guide builds on.

The docs’ own example session shows the squeeze. Before /compact, 22,225 tokens are in use. After it, 17,095 tokens remain, made up of the startup content reloaded from disk, the four files Claude had read, an invoked skill body, and a conversation summary of only 1,725 tokens. Everything you said during the session has to fit in that summary unless something puts it back.

Illustrative horizontal bar chart from Anthropic's example session: a gray bar of 22,225 tokens before /compact and a stacked bar of 17,095 tokens after, split into startup content 7,850, conversation summary 1,725, re-read files 6,900 and skill body 620.Illustrative horizontal bar chart from Anthropic's example session: a gray bar of 22,225 tokens before /compact and a stacked bar of 17,095 tokens after, split into startup content 7,850, conversation summary 1,725, re-read files 6,900 and skill body 620.
Illustrative docs example: after /compact the whole conversation survives as a 1,725-token summary, while most of what remains is startup content and re-read files. Source: Claude Code Docs, Explore the context window, fetched Nov 26, 2026.

To read the same breakdown for your own session, the Claude Code context window explainer walks through /context output category by category.

Decide whether you need a hook at all

Hooks are not always the simplest fix, and a setup you do not need is a setup you have to maintain. Match what must survive to the lightest tool that preserves it:

What must survive Simplest tool Why it works
A fixed rule such as “do not touch migrations/” A line in project-root CLAUDE.md Re-injected from disk after every compaction
A rule that currently lives in a path-scoped rule file Remove the paths: frontmatter or move the rule to root CLAUDE.md Path-scoped rules are summarized away with the conversation
What to emphasize in one particular compaction /compact focus on the billing tax move The summary keeps what you choose instead of what the automatic pass guesses
Standing guidance for every summary A “Compact Instructions” section in CLAUDE.md The documented way to control what compaction preserves
A plan written in plan mode Nothing extra The plan is re-injected from disk
Progress that changes hourly: current step, next step, files touched PreCompact save plus SessionStart compact inject Captures state at the moment compaction starts and restores it deterministically

A plain planning file covers part of the last row. Many people keep a task_plan.md or progress.md and add a CLAUDE.md line telling Claude to read it after compaction and keep it updated. Because root CLAUDE.md reloads from disk, the pointer always survives. The weakness is that the pointer depends on Claude choosing to open the file. The hooks guide’s core argument is that hooks make certain actions always happen rather than relying on the model to choose them, and the SessionStart hook puts the content itself into context. If your sessions are short or you compact by hand with a focus line, the planning file alone is often enough.

For task:billing-refactor-01 this guide uses both layers: the hard rule goes in CLAUDE.md, where it reloads regardless of any hook, and the changing progress travels through the two hooks. If either layer fails, the other still carries the most important line.

Prepare the project for task:billing-refactor-01

The worked case is illustrative. A TypeScript billing service is moving tax calculation out of src/billing/invoice.ts into a new src/billing/tax.ts without changing any invoice totals. Steps one to three are done. Step four, updating src/billing/credit-note.ts, is next. Nothing under migrations/ may change, because schema work goes through a separate reviewed pull request.

  1. Create the directories the hooks will use: mkdir -p .claude/hooks .claude/state
  2. Write the task file that you, or Claude at your instruction, keep current. Save it as .claude/state/task.md:
# Current task: task:billing-refactor-01
Goal: move invoice tax calculation from src/billing/invoice.ts into src/billing/tax.ts without changing totals.
Done: steps 1-3 (extract calculateTax, add tax.test.ts, switch the invoice.ts import)
Next step: 4 of 5. Update src/billing/credit-note.ts to call tax.ts, then run the billing tests.
Rules:
- Do not touch migrations/ (schema changes go through a separate reviewed PR).
- Keep the exported signatures in src/billing/index.ts unchanged.
- Run the billing tests before reporting a step done.
  1. Add the durable layer to your project-root CLAUDE.md:
## Billing refactor rules
- Never edit files under migrations/.
- Keep .claude/state/task.md current: when a step finishes, update Done and Next step before starting the next one.
  1. Keep the generated snapshot out of git, since it records a session ID and changes on every compaction: echo '.claude/state/progress.md' >> .gitignore

Keep task.md short. It is the raw material for the restored block, and the injector caps what it prints, so every extra paragraph pushes the important lines toward the cut-off. Five to twelve lines is a good target: the task label, the goal, what is done, the next concrete step and the rules.

Write the PreCompact save script

Save this as .claude/hooks/precompact-save.sh. It runs just before compaction, receives the hook input as JSON on stdin, and writes .claude/state/progress.md.

#!/bin/bash
# precompact-save.sh: snapshot task state before Claude Code compacts.
# Called by PreCompact hooks. $1 is "manual" or "auto", set per matcher in settings.json.
set -u

TRIGGER="${1:-unknown}"
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
STATE_DIR="$PROJECT_DIR/.claude/state"
TASK_FILE="$STATE_DIR/task.md"
OUT_FILE="$STATE_DIR/progress.md"

INPUT=$(cat)
if command -v jq >/dev/null 2>&1; then
  SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // "unknown"')
else
  SESSION_ID="unknown (jq not installed)"
  echo "precompact-save: jq not found; session id not recorded" >&2
fi

mkdir -p "$STATE_DIR"
TMP_FILE=$(mktemp "$STATE_DIR/progress.XXXXXX")

{
  echo "saved_epoch: $(date +%s)"
  echo "saved_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo "event: PreCompact ($TRIGGER)"
  echo "session: $SESSION_ID"
  echo
  if [ -f "$TASK_FILE" ]; then
    cat "$TASK_FILE"
  else
    echo "No task file at .claude/state/task.md"
  fi
  echo
  echo "Files changed since last commit:"
  git -C "$PROJECT_DIR" diff --name-only HEAD 2>/dev/null | head -n 10 | sed 's/^/- /'
} > "$TMP_FILE"

mv "$TMP_FILE" "$OUT_FILE"
echo "precompact-save: wrote $OUT_FILE ($TRIGGER)" >&2
exit 0

The choices that matter:

  1. The trigger comes from an argument, not a parsed field. The hooks guide documents that PreCompact matchers filter on what triggered compaction, manual or auto. Registering one matcher group per trigger and passing the word as $1 records the trigger without depending on any input field name beyond the common session_id.
  2. CLAUDE_PROJECT_DIR anchors every path. Hooks may run from a different working directory than you expect, and the guide’s own examples reference scripts through $CLAUDE_PROJECT_DIR. The $(pwd) fallback only exists so you can test the script by hand.
  3. The write is atomic. The script builds the snapshot in a temporary file and renames it, so a half-written progress.md never reaches the injector if the hook is interrupted.
  4. Nothing goes to stdout. Diagnostics go to stderr, which the guide notes keeps stdout clean and sends the message to the debug log. The PreCompact hook’s job is to write the file, not to talk to Claude.
  5. saved_epoch comes first. The injector reads that line to decide whether the snapshot is stale.
  6. The changed-file list is capped at ten. git diff --name-only HEAD covers staged and unstaged edits to tracked files; new untracked files do not appear. Ten names is enough to remind Claude where it was working.

Write the SessionStart compact injector

Save this as .claude/hooks/postcompact-inject.sh. It runs when the session restarts after compaction, and whatever it prints to stdout is added to Claude’s context.

#!/bin/bash
# postcompact-inject.sh: print a short, capped state block after compaction.
# Called by a SessionStart hook with matcher "compact". Plain stdout is added to Claude's context.
set -u

PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
STATE_FILE="$PROJECT_DIR/.claude/state/progress.md"
MAX_CHARS=1500
MAX_AGE_SECONDS=21600   # 6 hours

cat > /dev/null   # read and discard the hook input on stdin

if [ ! -f "$STATE_FILE" ]; then
  echo "Post-compaction note: no saved state at .claude/state/progress.md. Ask the user for the current task before editing files."
  exit 0
fi

SAVED=$(sed -n 's/^saved_epoch: //p' "$STATE_FILE" | head -n 1)
NOW=$(date +%s)
AGE=$(( NOW - ${SAVED:-0} ))

echo "Post-compaction state (restored from .claude/state/progress.md, saved ${AGE}s ago):"
if [ "$AGE" -gt "$MAX_AGE_SECONDS" ]; then
  echo "WARNING: this snapshot is older than 6 hours and may be stale. Confirm the task with the user."
fi
head -c "$MAX_CHARS" "$STATE_FILE"
echo
echo "[end of restored state]"
exit 0

Why it is built this way:

  1. Plain text, exit 0. The hooks guide states that for SessionStart hooks exiting 0, Claude Code adds stdout it treats as plain text to Claude’s context. No JSON envelope is needed, which also avoids the guide’s warning about shell-profile output corrupting JSON.
  2. A hard character cap. head -c 1500 bounds the block no matter how large task.md grows. Claude Code v2.1.332 does shorten very large hook output (text over about 50,000 characters) in some blocking and failure cases, but that is a crash guard, not a budget. Set your own ceiling. head -c counts bytes, so keep task.md in plain ASCII or a multibyte character may be cut in half.
  3. A staleness check. If the snapshot is older than six hours, or saved_epoch is missing so the age computes as huge, the block arrives with a warning instead of passing old instructions off as current.
  4. A missing-file branch that still says something. If progress.md does not exist, Claude is told to ask rather than guess.
  5. Clear framing lines. The header and the [end of restored state] line make the block easy to find when you ask Claude to quote it during verification.

Why SessionStart rather than PostCompact? The guide lists a PostCompact event that fires after compaction completes and accepts the same manual and auto matchers. But its list of events whose plain stdout is added to context names SessionStart, not PostCompact, and the context-window page documents SessionStart hooks matching compact as the mechanism whose output joins the compacted context. Use PostCompact for side effects such as appending to a log; use SessionStart compact for anything Claude must read.

Register both hooks in .claude/settings.json

Add this to .claude/settings.json in the project root. If the file already has a hooks key, add PreCompact and SessionStart as siblings of the existing event keys rather than replacing the object, as the guide instructs.

{
  "hooks": {
    "PreCompact": [
      {
        "matcher": "manual",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/precompact-save.sh manual"
          }
        ]
      },
      {
        "matcher": "auto",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/precompact-save.sh auto"
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/postcompact-inject.sh"
          }
        ]
      }
    ]
  }
}

Then register and confirm:

  1. Make both scripts executable, which the guide requires on macOS and Linux: chmod +x .claude/hooks/precompact-save.sh .claude/hooks/postcompact-inject.sh
  2. Validate the JSON before Claude Code reads it: jq . .claude/settings.json > /dev/null && echo ok. Trailing commas and comments are not allowed.
  3. Type /hooks at the Claude Code prompt. You should see two entries under PreCompact and one under SessionStart. The file watcher normally picks up edits automatically; if the entries do not appear after a few seconds, restart the session.
  4. Decide on scope. .claude/settings.json is shared with everyone who clones the repository. To keep the hooks personal, put the same block in .claude/settings.local.json; to run them in every project, use ~/.claude/settings.json and point the commands at scripts in your home directory.

Keep the compact matcher. Without a matcher, SessionStart fires on every source the guide lists (startup, resume, clear, compact and fork), and the restored block would appear in fresh sessions where an old snapshot could mislead Claude. Matchers are case-sensitive, so Manual or Compact never match.

Top of the Claude Code Docs page titled Automate actions with hooks.
Anthropic's Claude Code Docs page "Automate actions with hooks", the guide whose settings syntax, matchers and troubleshooting steps this tutorial follows. Source: Anthropic, Claude Code Docs. · Original source

Here is the full path the state takes through one compaction:

Diagram of the PreCompact and SessionStart compact hooks: task.md feeds the PreCompact hook, which writes progress.md; compaction summarizes the conversation; the SessionStart compact hook reads progress.md and sends a capped block to Claude's next turn, with a warning branch when the file is stale or missing.Diagram of the PreCompact and SessionStart compact hooks: task.md feeds the PreCompact hook, which writes progress.md; compaction summarizes the conversation; the SessionStart compact hook reads progress.md and sends a capped block to Claude's next turn, with a warning branch when the file is stale or missing.
Illustrative flow for task:billing-refactor-01. State you wrote to progress.md, not the summary, carries the task across compaction. Event and matcher names from Anthropic's Claude Code hooks guide.

When you share hooks through a repository, treat them as code that runs on teammates’ machines. The guide’s security considerations apply, and the guide to unauthored agent hooks covers how to audit hook entries nobody on the team wrote.

Test the scripts before Claude Code runs them

The guide’s troubleshooting advice is to pipe sample JSON into a hook and check the exit code. Do that for both scripts from the project root:

# 1. Save step, simulating a manual compaction
echo '{"session_id":"test-01","hook_event_name":"PreCompact"}' \
  | CLAUDE_PROJECT_DIR="$PWD" .claude/hooks/precompact-save.sh manual
echo "exit: $?"
head -n 4 .claude/state/progress.md

# 2. Inject step, measuring the output size
echo '{"session_id":"test-01","hook_event_name":"SessionStart"}' \
  | CLAUDE_PROJECT_DIR="$PWD" .claude/hooks/postcompact-inject.sh | wc -c

# 3. Missing-file branch
mv .claude/state/progress.md /tmp/progress.bak
echo '{}' | CLAUDE_PROJECT_DIR="$PWD" .claude/hooks/postcompact-inject.sh
mv /tmp/progress.bak .claude/state/progress.md

Illustrative expected output, not a recorded run:

precompact-save: wrote /home/you/billing/.claude/state/progress.md (manual)
exit: 0
saved_epoch: 1795702400
saved_at: 2026-11-26T14:13:20Z
event: PreCompact (manual)
session: test-01
1032
Post-compaction note: no saved state at .claude/state/progress.md. Ask the user for the current task before editing files.

Read those results like this:

  • [ ] The first line arrives on stderr and names the trigger you passed. If you see jq not found instead, install jq before going further.
  • [ ] exit: 0 confirms the save script never blocks. Any other code would show up as a hook error in the transcript.
  • [ ] The first four lines of progress.md carry a fresh epoch, a UTC time, the trigger and the session ID. The epoch and the UTC time describe the same instant.
  • [ ] The byte count from step two stays under roughly 1,600: the 1,500-byte cap plus the header and footer lines. A much larger number means the cap is not applied.
  • [ ] Step three prints the missing-file note instead of an error.

Run the worked example through /compact

With the scripts passing by hand, run the real cycle in a Claude Code session on the billing repository.

  1. Start Claude Code and run /context. Note the total so you can compare after compaction.
  2. Work normally until the task file says step four is next, or edit task.md to that state for the test.
  3. Type /compact. This fires the PreCompact hook with the manual matcher, then compaction, then the SessionStart hook with the compact matcher.
  4. In a second terminal, run head -n 4 .claude/state/progress.md and confirm the time is a few seconds old.
  5. Ask Claude a question that only the restored block answers, then ask it to quote the block’s first line.
  6. Run /context again and compare.
Input Action Expected result
task:billing-refactor-01 with task.md at step 4 of 5, next step “update src/billing/credit-note.ts” Type /compact in the session .claude/state/progress.md is rewritten; its first lines show a new saved_epoch and event: PreCompact (manual) followed by the task.md text (illustrative expected observation)
The same session, immediately after compaction Ask: “What is the current task, the next step, and which directory is off-limits?” Claude names task:billing-refactor-01, step 4 on credit-note.ts and migrations/ without you restating any of them (illustrative expected observation)
The same session Ask: “Quote the line that starts with Post-compaction state” Claude quotes the header with a small age, such as “saved 3s ago”, which proves the SessionStart compact hook output reached context (illustrative expected observation)
task.md trimmed to nine lines, injector cap MAX_CHARS=1500 Run /context before and after /compact The restored block adds only a small amount compared with the conversation summary; nothing about it dominates the breakdown (illustrative expected observation)
The same repository after a long session with no manual compaction Let auto-compaction run, then head -n 3 .claude/state/progress.md The event line reads event: PreCompact (auto), showing the second matcher group fired (illustrative expected observation)
progress.md edited so saved_epoch: 0 Run the injector by hand as in the test section Output includes the line “WARNING: this snapshot is older than 6 hours and may be stale” (illustrative expected observation)

If Claude answers the first question correctly but cannot quote the header, it probably got the rule from CLAUDE.md rather than the hook. That is the two-layer design working, but it means the hook path still needs fixing: go to the troubleshooting table.

One more behavior to know: if a single file or tool output is so large that context refills right after each summary, Claude Code stops auto-compacting after a few attempts and shows a thrashing error instead of looping. A small injected block will not cause that, but a 20,000-character task file could contribute to it. The cap is there for that reason too.

Troubleshoot a hook that does not fire or injects too much

Most failures trace back to the settings file, the script’s permissions or a matcher. Work down this table:

Symptom Likely cause Fix
/hooks shows nothing under PreCompact or SessionStart Invalid JSON, wrong file location, or the watcher missed the edit Run jq . .claude/settings.json; confirm the file is at .claude/settings.json in the project root; restart the session
/hooks says only hooks from managed settings run here Your organization set allowManagedHooksOnly Project and user hooks will not run; ask the admin, or rely on the CLAUDE.md layer
Hooks are listed but progress.md never changes Script not executable, or matcher typo such as Manual chmod +x both scripts; matchers are case-sensitive, so use manual, auto and compact exactly
Transcript shows a hook error mentioning “command not found” Relative script path Keep the "$CLAUDE_PROJECT_DIR"/... form, or use an absolute path
session: unknown (jq not installed) in the snapshot jq missing from the hook’s PATH Install jq; on Windows install it where Git Bash can find it
Error mentions Git Bash was not found Native Windows without Git Bash Follow the guide’s fixes for failed hooks on Windows without Git Bash, or run Claude Code inside WSL
Restored block appears in brand-new sessions SessionStart matcher missing or empty Set the matcher to compact
Claude restates an old step task.md was not updated, or the snapshot is old Update task.md; check the age in the header; keep the CLAUDE.md line asking Claude to update it
The block crowds the summary task.md grew into a diary Trim task.md to essentials; lower MAX_CHARS; recheck /context
Nothing obvious is wrong Need execution detail Start with claude --debug-file /tmp/claude.log, trigger /compact, and tail -f /tmp/claude.log in another terminal

Press Ctrl+O to open the transcript view while testing. A successful command hook usually shows nothing there, which is why the guide recommends checking for the hook’s effect, in this case the fresh progress.md and Claude’s ability to quote the header. A non-blocking failure appears as a hook error notice.

Roll back cleanly

You can remove the setup in a few minutes, and you can pause it without deleting anything.

  1. Pause everything temporarily: add "disableAllHooks": true to a settings file. This stops all hooks, not just these two. Claude Code reads the value left after settings precedence applies, so a project file can override yours, and hooks in managed settings still run unless the flag is also set there.
  2. Remove just this setup: delete the two PreCompact matcher groups and the SessionStart group with the compact matcher from .claude/settings.json, leaving any other hooks in place.
  3. Confirm: run /hooks and check that neither event lists the scripts.
  4. Delete the state: rm -f .claude/state/progress.md, and remove task.md if you no longer want it.
  5. Delete the scripts: rm .claude/hooks/precompact-save.sh .claude/hooks/postcompact-inject.sh
  6. Decide on the CLAUDE.md lines: keep the migrations rule, which is useful without hooks, and remove the instruction to update task.md if that file is gone.

Rollback leaves no residue in Claude Code itself. The hooks are plain settings entries and two files, and compaction falls back to its default behavior the moment they are gone.

How OpenCode handles the same problem

The X article that prompted this guide also links OpenCode’s compaction documentation, and the comparison clarifies what the Claude Code hooks are compensating for. OpenCode summarizes the whole conversation when a session approaches the model’s limit, but it also keeps the most recent conversation, about 15,000 tokens by default, beside the summary so exact recent details remain available. Its summary is structured so another agent could pick up the work, with sections such as Objective and Next Move covering decisions, active work, blockers and relevant files. After compaction, the current versions of your instruction files become the session’s baseline.

The levers are configuration rather than hooks:

{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "auto": true,
    "keep": { "tokens": 24000 },
    "buffer": "20%"
  }
}

Raising keep.tokens preserves more exact recent detail at the cost of room for new work, and a larger buffer compacts earlier. OpenCode’s page calls compaction lossy and recommends increasing keep.tokens or requesting compaction yourself before the automatic one when exact details matter. The compaction page does not describe a hook equivalent to PreCompact, so the portable part of this guide is the task file and the instruction-file rule, not the scripts.

Keep the setup honest over time

A state file that nobody updates is worse than none, because it restores yesterday’s plan with confidence. Run this checklist whenever a task changes:

  • [ ] Update task.md when a step finishes, or confirm Claude did it as CLAUDE.md asks.
  • [ ] Glance at the header age after each compaction; anything over an hour on an active task means the save hook did not fire.
  • [ ] Keep hard rules in CLAUDE.md as well as task.md, so a hook failure cannot remove them.
  • [ ] Re-run the three test commands after upgrading Claude Code, since compaction behavior changes between releases.
  • [ ] Treat the restored block as input, not authority. On unattended lanes, the guide to linting compaction summaries explains why summaries need checks before an agent acts on them.
  • [ ] If a session runs without you watching, decide who owns compaction first; agent-owned compaction policy covers notice, warn and force options.

The pattern generalizes. A subagent that works in its own context window, set up as in custom Claude Code subagents, keeps large reads out of yours and reduces how often compaction runs at all. The broader practice of deciding what enters context, and when, is the subject of the context engineering playbook. And once several sessions each carry their own state files, the AgentOps guide is the place to think about watching them as a fleet rather than one terminal at a time.

Sources

YOU'RE THROUGH THIS ONE.

Keep connecting the dots.

Back to the library

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater