AnthropicClaude Certified Architect – Foundations2026-105.4 Manage context effectively in large codebase exploration
Compact discovery and restore critical facts
Completed by the knowledge check
Learning objective
Use /compact to reclaim context after verbose discovery, then verify and re-inject critical facts not reliably preserved by summarization.
Core idea
For a long codebase investigation, compaction should remove discovery noise while preserving the evidence needed for the next decision. Use /context to inspect what occupies the window, save important findings, and run /compact with a focus instruction. Afterwards, check exact facts against the saved record and relevant code, then supply them again when the summary is insufficient.
Compaction summarizes; it does not turn conversation history into an exact evidence archive. Anthropic describes the risk that aggressive compression loses subtle details whose importance becomes apparent later. File paths, unusual class names, negative findings, and unresolved dependencies can matter more than a broad architectural summary suggests.
See 5.4.2 for the scratchpad’s contents. This lesson owns the transition from a crowded discovery conversation to a usable continuation, including /context and a PreCompact preservation hook. See 3.1.4 for diagnosing loaded instruction files.
How it works
Inspect before choosing the remedy
Claude Code’s /context command visualizes context usage as a colored grid and provides optimization suggestions for context-heavy tools, memory bloat, and capacity warnings. Use it to distinguish accumulated discovery from another source of overhead before choosing compaction.
If searches, file contents, and command output dominate a session you still need to continue, /compact fits that problem. If the next task is unrelated, /clear starts a conversation with empty context. The two commands have different continuity goals: compressing a useful investigation and starting a different one.
Do not treat a vague answer alone as proof that a particular token threshold has been reached. Context inspection shows usage, while answers that abandon exact discovered symbols show a quality problem. Together they help you decide to preserve evidence and remove irrelevant material rather than repeat the same specificity instruction.
Save what must survive
Before compacting, require the coordinator to update its findings file. Preserve exact symbols, paths, dependency edges, verification scope, decisions, and open questions. The file provides a recoverable record if the summary retains the architecture but drops the detail that distinguishes two implementations.
Claude Code supports /compact [instructions]. A focused command might be /compact Keep refund entry points, exact class names and paths, verified dependency edges, and unresolved callers. This tells the summarizer what to prioritize; it is not a replacement for saving or checking those details.
You can also put standing compaction guidance in the project-root CLAUDE.md. For this investigation, preserve the facts the next phase needs rather than every search and failed lead. To summarize only a stretch of discovery, run /rewind or press Esc twice, select a checkpoint, and choose Summarize from here or Summarize up to here.
Archive evidence with PreCompact
Claude Code fires PreCompact before a compact operation. Configure hooks.PreCompact in the project’s .claude/settings.json: matcher manual corresponds to /compact, and matcher auto corresponds to automatic compaction. A type: "command" hook can run your preservation script, which reads its JSON input and archives the identified transcript or saved findings.
The input includes session_id, transcript_path, and cwd, plus the event-specific fields trigger and custom_instructions. For manual compaction, custom_instructions contains the supplied focus text, or null if none was supplied. It is null for automatic compaction. These identifiers let your script associate an archive with the session and compaction trigger.
An archive is raw evidence, not automatically a verified findings file. A script that copies transcript_path saves the available transcript; a later loading step still has to select the useful facts. Keep continuous scratchpad maintenance as the normal path, with the hook preserving material that might otherwise disappear from accessible working context.
PreCompact can block compaction with exit code 2 or JSON decision: "block". Claude Code discards that hook’s systemMessage and continue fields. Do not use them to try to reload facts. Blocking automatic compaction can also prevent recovery: when it follows an API context-limit error, that underlying error surfaces and the request fails. Prefer a preservation action that allows successful compaction after saving the evidence.
Verify and re-inject after compaction
Run /context again to check usage after the operation. That confirms the resource effect, not the summary’s completeness. Claude Code preserves different kinds of context through different mechanisms:
| Context | After compaction |
|---|---|
Project-root CLAUDE.md, unscoped rules, auto memory, and the plan-mode plan | Re-injected from disk |
| Files Claude read or edited | Up to five re-read, most recently modified first; a file over 5,000 tokens returns as a Referenced file path without content |
Nested CLAUDE.md and rules with paths: frontmatter | Summarized with message history, then reloaded on demand when their file triggers apply |
| Context injected by earlier hooks | Summarized with the conversation |
SessionStart hooks matching compact | Run again and add their output to the compacted context |
Do not assume the discovery scratchpad is among the five re-read files or that its entire content returns. Compare the facts needed for the next question with the saved record and reopen source passages when a detail is missing or the code has changed.
For an automated check, configure a PostCompact command hook with matcher manual or auto. Its compact_summary input contains the generated summary. Your script can check that text for the scratchpad’s must-keep identifiers and log omissions; identifier presence alone does not prove the relationships are correct. PostCompact cannot change the compaction result or inject replacement context, and its systemMessage and continue fields are discarded.
For manual recovery, ask Claude to read the relevant findings section before continuing. For a repeatable loading step, configure SessionStart with matcher compact. It runs after automatic or manual compaction and can return hookSpecificOutput.additionalContext with hookEventName: "SessionStart" to supply a concise verified summary.
Keep that reinjected summary small. Claude Code caps additionalContext at 10,000 characters. For longer values, it supplies a saved-file path and a preview of up to 2,000 characters without asking Claude to read the file. Keep essential facts inside the cap and require explicit reads for detail.
Key distinctions and trade-offs
Context inspection versus compaction: /context shows usage and optimization suggestions. /compact changes the conversation representation by summarizing it.
Focus instruction versus preservation: A focus instruction guides what the summary keeps. A scratchpad or transcript archive retains material independently of that choice.
Preservation versus verification versus loading: PreCompact saves evidence, PostCompact checks compact_summary, and SessionStart with matcher compact can supply context after compaction. Saving or checking alone does not reload the facts.
Compaction preserves useful continuity but can omit important detail. A fresh conversation avoids inherited noise but requires an explicit handoff. Choose according to whether the next investigation needs the existing conversation or only its verified findings.
Architecture / decision scenario
A developer productivity session has read many files while tracing a refund flow. /context shows substantial conversation usage after verbose discovery. The engineer wants to continue into duplicate-refund analysis, so the coordinator first updates its scratchpad with exact call sites, dependency edges, and the unresolved job callers.
A PreCompact command hook archives the transcript identified by transcript_path. The engineer runs a focused /compact command and checks /context again. A PostCompact script checks compact_summary against the saved identifiers and flags the omitted restocking path.
Before delegating duplicate-refund analysis, the coordinator reads the saved finding and verifies the relevant source passage. It supplies the exact ledger method and separate restocking path again. A SessionStart hook matched on compact can automate loading that concise record; the preservation hook itself does not perform this post-compaction injection.
The investigation continues with reclaimed space and restored evidence. Repeating the summary without checking it would carry the omitted dependency into the next design decision.
Common exam traps
- Running
/compactbefore persisting critical discoveries. - Treating focus instructions as a guarantee of exact fact retention.
- Assuming a lower
/contextreading proves semantic completeness. - Assuming a reread rule in nested
CLAUDE.mdis re-injected like the project-root file. - Confusing a
PreCompacttranscript archive with verified, reloaded findings. - Trying to inject recovery facts through discarded
PreCompactfields. - Blocking context-limit recovery indefinitely instead of saving evidence and permitting compaction.
What to remember
Inspect, persist, compact, and verify. Use PreCompact to preserve evidence, PostCompact to check the generated summary, and an explicit read or SessionStart loading step to restore selected facts. Reclaimed space and preserved correctness require separate checks.
Knowledge check
/context shows that search results and file contents fill most of a session’s window. The engineer wants to continue the same refund investigation into duplicate-refund analysis. Which sequence fits?
/clear , then continue the investigation from an empty context/compact , then check facts against it/compact , then update the findings file from the summary it produces/compact with focus instructions and treat its summary as the investigation record/clear suits an unrelated next task rather than a continuation, updating the file from the summary saves only what survived, and focus instructions guide the summary without guaranteeing exact retention.A team wants a concise, verified findings summary loaded into Claude Code’s context automatically after every compaction. Which hook configuration does that?
PreCompact , returning the summary in its systemMessage fieldPostCompact , returning the summary after it checks compact_summarySessionStart with matcher compact , returning additionalContextSubagentStart , returning the summary in its additionalContext fieldSessionStart with matcher compact runs after manual or automatic compaction and can add context through hookSpecificOutput.additionalContext . PreCompact and PostCompact both discard systemMessage , and PostCompact cannot change the compaction result; SubagentStart adds context to a starting subagent, not to the compacted main session.A PreCompact command hook exits with code 2 whenever the findings file is more than ten minutes old. Some requests now fail with a context-limit error instead of compacting. What should the hook do instead?
decision: "block" in place of exiting with code 2systemMessage , and then block compactionPreCompact discards systemMessage , so it cannot reload facts either.After a focused /compact, /context shows a much lower usage reading. The next step depends on a separate restocking path recorded in the findings file. How should the team confirm the summary kept it?
/context for the reduction in usage after the compactionPostCompact script can check compact_summary for must-keep identifiers, and the coordinator re-supplies anything missing.References
- Anthropic, Built-in commands
- Anthropic, Hooks reference
- Anthropic, Best practices for Claude Code
- Anthropic, Effective context engineering for AI agents
- Anthropic, Explore the context window