Skip to content

Context, memory, compaction, checkpoints, and rewind

This page reverse-engineers how cli.renamed.js manages model-visible context and memory, how conversation compaction works, and which checkpoint/rewind surfaces are source-confirmed.

Scope: local/project/managed/auto memory, context accounting, manual and automatic compaction, compaction hooks, transcript context-collapse state, file checkpoints, --rewind-files, and the absence of a general source-confirmed undo command in this build.

Source anchors

Semantic aliasString or symbolMeaning
ManagedMemoryInjectionCLAUDE.md-style instructions injected as organization-managed memoryManaged/policy memory can inject CLAUDE.md-style instructions.
MemoryScopeResolverUser, Local, Project, Managed, AutoMem in getMemoryPathMemory path resolver for global, local, project, managed, and auto-memory scopes.
ProjectRuleMemoryLoader.claude/rules, CLAUDE.local.mdProject/local rule and memory loading path.
AutoMemoryNormalizerif(q==="AutoMem")w=Dr$(O).contentAuto-memory content is normalized before becoming memory context.
DynamicPromptBoundary__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__Runtime distinguishes stable and dynamic system-prompt sections.
PromptCacheMetadataGuardcache_controlPrompt-cache metadata is stripped/hardened for hashing/accounting paths.
MemoryRelevanceRequestSelect memories relevant to:Memory relevance request; uses a helper model and omits the normal system prefix.
AutoMemoryFactExtractionExtract facts relevant to:Auto-memory/fact extraction request path.
AutoCompactSettingautoCompactEnabledUser setting: automatically compact when context fills.
AutoCompactUserExplanationAuto-compact summarizes the conversation when context usage approaches this limitUser-visible /autocompact explanation.
AutoCompactGateDISABLE_COMPACT, DISABLE_AUTO_COMPACT, autocompact: tokens=Auto-compact gate and threshold calculation.
CompactionHookLifecyclePreCompact, PostCompactHook lifecycle around compaction.
PreCompactHookSchemaPreCompact, trigger, custom_instructionsHook schema for manual/auto compaction and hook-provided instructions.
PostCompactSummaryHookcompact_summaryPostCompact hook receives the produced summary.
PrecomputedCompactionprecomputed compact: startedBackground/precomputed compaction path.
ReactiveCompactionBlockReactive compact blocked by PreCompact hookReactive compaction path and hook-block behavior.
CompactionSummaryFailureFailed to generate conversation summaryFull compaction failure when no valid summary is returned.
PartialCompactionFailuretengu_partial_compact_failedPartial compaction failure path.
ContextLowWarningContext low ... Run /compact to compact & continueTUI context-low warning and manual compaction prompt.
ContextCollapseStatecontextCollapseCommits, contextCollapseSnapshotContext-collapse state is persisted/restored with session state.
FileCheckpointSettingfileCheckpointingEnabledFile snapshot setting used by /rewind.
FileHistoryRewindFileHistory: [Rewind] Rewinding to snapshotFile rewind implementation applies a tracked snapshot.
HeadlessRewindGuardError: --rewind-files requires --resumeHeadless rewind guard.
RewindSuccessFrameFiles rewound to state at message--rewind-files success path.

Runtime context model

cli.renamed.js treats context as layered runtime state, not as one static prompt string.

flowchart TD
Files[CLAUDE.md / CLAUDE.local.md / .claude/rules] --> Memory[Memory entries]
Managed[Managed claudeMd policy] --> Memory
Auto[AutoMem] --> Memory
Settings[Settings / output styles / tools / MCP / agents] --> Context[Context assembler]
Memory --> Selector[Memory relevance and fact extraction]
Selector --> Context
Transcript[Session transcript and tool results] --> Context
Context --> Budget[Context accounting]
Budget --> Compact{Compact needed?}
Compact -->|no| Request[Provider request]
Compact -->|yes| Summary[Compaction summary]
Summary --> Request

The main memory families are:

Memory familySource-confirmed rootsRuntime role
User/global memoryCLAUDE.md under the user config rootPrivate instructions across projects.
Project memoryproject CLAUDE.md, project .claude/rulesChecked-in or project-scoped instructions.
Local memoryCLAUDE.local.mdPrivate project instructions, gated by local-settings support.
Managed memorymanaged/policy CLAUDE.md or claudeMd settingOrganization-managed instructions that ordinary user/project excludes cannot remove.
Auto memoryAutoMem path resolved by XZH, normalized by Dr$Persistent auto-memory across conversations.

The memory loader can exclude user/project/local files with configured glob patterns, but the schema text explicitly says managed/policy files cannot be excluded through that mechanism.

Memory selection is not memory compression

Two helper prompts are important:

  • Select memories relevant to:
  • Extract facts relevant to:

Both use model:iv() and skipSystemPromptPrefix:!0 in the source anchors around lines ~1975-1976. That means memory relevance and fact extraction are their own lightweight model requests, not normal conversation turns with the full default system prompt.

This is different from compaction:

MechanismWhat it changesWhat it does not imply
Memory selectionChooses or extracts relevant memory facts for the current prompt.Does not rewrite the whole transcript.
AutoMem normalizationCleans/normalizes auto-memory content before use.Does not prove every memory file is summarized.
Context compactionSummarizes conversation history so the agent can continue inside the context window.Does not mean CLAUDE.md files themselves are compressed.

So “memory compression” in this build is best described as conversation/context compaction plus memory re-selection, not as an in-place compression of memory files.

Context accounting and auto-compact thresholds

Context accounting uses model-aware token/window logic. The visible surfaces include:

  • autoCompactEnabled: persistent setting, defaulted on in global config.
  • autoCompactWindow: configurable window size.
  • CLAUDE_CODE_AUTO_COMPACT_WINDOW: environment override surfaced by /autocompact UI.
  • DISABLE_COMPACT and DISABLE_AUTO_COMPACT: environment kill switches.
  • UI text such as Context low (...) · Run /compact to compact & continue.

p15(...) computes the current token estimate, calls ONH(...), logs autocompact: tokens=<n> level=<level> effectiveWindow=<n>, and returns true for compact or blocked levels. That makes compaction a runtime decision based on token pressure and the selected model/window, not just a slash command.

Manual, automatic, precomputed, and reactive compaction

Compaction has several source-confirmed variants:

VariantTriggerConfirmed anchorsBehavior
Manual compaction/compact or command binding such as command:compactContext low ... Run /compact, command:compactUser-controlled summary/rewrite of conversation context.
Auto compactionContext approaches the configured/model-capped windowautoCompactEnabled, autocompact: tokens=Runtime starts compaction without the user explicitly typing /compact.
Precomputed compactionBackground preparation before the hard limitprecomputed compact: startedStarts a compaction attempt ahead of need; caches or discards the result depending on hooks/abort/failure.
Reactive compactionRequest is about to be blocked by context pressureReactive compact blocked by PreCompact hookRuns compaction synchronously enough to unblock continuation when possible.
Partial compactionSome context is compacted while preserving a boundarytengu_partial_compact_failedUsed when full compaction is not the right shape or a boundary marker must be kept.

Hook lifecycle

Compaction is hookable:

  1. PreCompact receives trigger: "manual" | "auto" and nullable custom_instructions.
  2. A hook can block compaction (blockedBy) or provide newCustomInstructions.
  3. The runtime summarizes the current conversation/context.
  4. PostCompact receives compact_summary.
sequenceDiagram
participant ModelLoop as Model loop
participant Hooks as Hook runner
participant Model as Summary model request
participant State as Context/session state
ModelLoop->>Hooks: PreCompact(trigger, custom_instructions)
alt hook blocks
Hooks-->>ModelLoop: blockedBy
ModelLoop-->>State: keep existing context
else hook allows
Hooks-->>ModelLoop: newCustomInstructions?
ModelLoop->>Model: summarize conversation/context
Model-->>ModelLoop: compact summary
ModelLoop->>State: replace/collapse older context
ModelLoop->>Hooks: PostCompact(compact_summary)
end

What compaction rebuilds afterward

After a valid summary, the full and partial compaction paths clear transient read/memory-selection state and rebuild context contributors. The source near tengu_compact_failed and tengu_partial_compact_failed shows calls that clear readFileState, clear loadedNestedMemoryPaths, reset the memorySelector, then re-add memory/tool/agent/MCP context fragments.

This is the key design point: compaction is not only “summarize old messages.” It also refreshes the non-message context surface so the next provider request has a compact transcript plus current tool, memory, MCP, and agent instructions.

Failure behavior

FailureSource-confirmed behavior
Prompt still too longCompaction retries can drop older messages and continue with fewer remaining messages.
No valid summary textThrows Failed to generate conversation summary - response did not contain valid text content.
API error in summary callEmits tengu_compact_failed / tengu_partial_compact_failed with reason:"api_error".
Hook blocks compactionPrecomputed/reactive compaction is abandoned and logged as blocked.
Compaction disabledUI shows context-low warnings and suggests /clear or manual trimming instead.

Checkpoint, rewind, and undo semantics

There are two separate “checkpoint-like” systems:

State familySource anchorsPurpose
Context-collapse statecontextCollapseCommits, contextCollapseSnapshotPersists compaction/collapse metadata with the session so resume can rehydrate the collapsed context.
File-history snapshotsfileCheckpointingEnabled, fileHistorySnapshots, FileHistory: [Rewind]Snapshots edited files before changes so the user can restore the file tree to a prior user-message point.

fileCheckpointingEnabled is described as “Snapshot files before edits so /rewind can restore them.” The actual rewind implementation looks up the latest snapshot for a message ID and applies tracked backups. The headless --rewind-files <user-message-id> path validates that the target is a user message, performs the rewind, prints Files rewound to state at message <id>, and exits without running another model turn.

Rewind is intentionally standalone

The headless runner rejects unsafe combinations before any model work:

GuardRuntime effect
--rewind-files without --resumeExits with Error: --rewind-files requires --resume.
--rewind-files plus a promptExits with Error: --rewind-files is a standalone operation and cannot be used with a prompt.
Target ID is not a user messageExits with Error: --rewind-files requires a user message UUID....

This makes rewind a file-restore operation tied to a resumed transcript, not a prompt modifier.

Is there undo?

For this build, the source-confirmed user-facing reversible operations are:

  • resume/continue/fork at the session layer;
  • context compaction/collapse at the prompt-history layer;
  • file checkpoint + /rewind / --rewind-files at the filesystem layer.

No high-signal CLI flag or slash command for a general undo operation was confirmed in the runtime anchors used for this page. Hits for undo in the bundle are mostly unrelated vendor/editor strings, so this page does not document a general undo feature as confirmed behavior.

Operational interpretation

The runtime manages continuity through three different persistence loops:

  1. Memory loop: load CLAUDE.md/rules/managed/AutoMem, select relevant memories, and inject them into context.
  2. Context loop: monitor token pressure, compact conversation history, and persist collapse metadata.
  3. Filesystem loop: snapshot edited files and allow rewind to a previous user-message boundary.

These loops cooperate but do not collapse into one mechanism. A compaction summary can keep the conversation moving, while file rewind can restore disk state, and resume can rehydrate both kinds of state later.

Caveats

  • cli.renamed.js is bundled/minified; function names such as p15, aq8, nj6, pA8, and XZH are version-specific search anchors, not public APIs.
  • This page documents local runtime surfaces. Hosted/managed-agent server-side compaction appears in embedded SDK docs and event examples, but local CLI behavior is anchored separately above.
  • Exact token thresholds are model- and setting-dependent; the source-confirmed behavior is the thresholding pipeline and user-visible controls, not one universal number.

Created and maintained by Yingting Huang.