Skip to lesson

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:

ContextAfter compaction
Project-root CLAUDE.md, unscoped rules, auto memory, and the plan-mode planRe-injected from disk
Files Claude read or editedUp 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: frontmatterSummarized with message history, then reloaded on demand when their file triggers apply
Context injected by earlier hooksSummarized with the conversation
SessionStart hooks matching compactRun 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.

Saving or checking alone does not reload the factsStarts at PreCompact, which fires before the compact operation and saves evidence to a transcript archive. The compact operation produces the compacted context and fans out to PostCompact, which receives compact_summary and logs omissions, and to SessionStart with matcher compact, which runs after compaction. Only SessionStart has an edge back: it adds additionalContext to the compacted context, while the archive and PostCompact never reach it.saves evidencecompact_summaryadditionalContextPreCompactTranscript archiveCompact operationCompacted contextPostCompactLog omissionsSessionStart withmatcher compact

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 /compact before persisting critical discoveries.
  • Treating focus instructions as a guarantee of exact fact retention.
  • Assuming a lower /context reading proves semantic completeness.
  • Assuming a reread rule in nested CLAUDE.md is re-injected like the project-root file.
  • Confusing a PreCompact transcript archive with verified, reloaded findings.
  • Trying to inject recovery facts through discarded PreCompact fields.
  • 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

References