Introducing a new way to review your PRs.

Read the announcement

thedotmack / claude-mem

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

View on GitHub

47 documents · Updated Nov 20, 2026

docs / automatic-context-clearing

Automatic context clearing

Automatic context clearing keeps a long interactive Claude Code task moving when its context window reaches a set limit. It asks Claude to save the current work state, clears the old conversation, and starts a fresh turn with continue so work can carry on with less context pressure.

Policy and eligibility

Automatic clearing is an opt-in policy. It only runs when both automatic clearing and work-state saving are enabled, and it only acts in an interactive session where a person can see and continue after the reset.

Configuration sources

The policy reads its settings from the normal claude-mem settings locations. Environment values take priority over settings.json, while a missing or invalid threshold uses the safe default of 33 percent. The threshold accepts values from 1 through 95 percent.

The feature remains off unless CLAUDE_MEM_AUTO_CLEAR_ENABLED is explicitly true and work-state support is also enabled through CLAUDE_MEM_WORK_STATE_ENABLED. This keeps a context reset from starting when there is no work state for the new conversation to use.

References: src/…/settings.ts• L9-18 src/…/settings.ts• L40-65

Threshold eligibility

The controller checks context use after main-conversation tool calls and after normal main-conversation turns. It ignores subagent activity, denied tool calls, non-interactive sessions, and conversations that have already been paused after a failed save or reset.

The first context check after an automatic reset has an extra safety rule. If the fresh conversation already meets the threshold, the controller disables automatic clearing until Claude Code restarts instead of entering a reset loop.

References: src/…/controller.ts• L110-128 src/…/controller.ts• L144-170 src/…/controller.ts• L189-211

Context reset flow

The reset flow preserves work before it removes conversation history. It uses the context threshold as a trigger, the work-state record as the handoff, and a new user turn as the restart point.

Save request

When a tool call pushes the main conversation to the threshold, the controller adds a request to that tool result. Claude is asked to stop new work and save the goal, decisions, files, and next step with work_state_write.

If a turn reaches the threshold without a tool call, the controller waits for the turn to end and then sends a separate save prompt. A successful save must be the latest relevant action before the reset can proceed.

References: src/…/controller.ts• L110-128 src/…/controller.ts• L144-165 src/…/controller.ts• L271-299

Clear and resume

After a successful save, the controller runs /clear and sends continue as the user's next message. The new conversation can then read the open work state and resume the task without carrying the old context window.

The clear and resume sequence is deferred until the current hook returns. This prevents the hook from blocking the turn that produced the save and lets the host create the fresh conversation before the continuation prompt is sent.

The following flow shows the normal handoff and the points where the controller stops without clearing:

flowchart TD
    A[Context reaches policy threshold] --> B[Ask Claude to save work state]
    B --> C{Successful work-state save?}
    C -- No --> D[Pause until the next /clear]
    C -- Yes --> E[Run /clear]
    E --> F{Clear succeeds?}
    F -- No --> D
    F -- Yes --> G[Send user continue]
    G --> H[Fresh conversation resumes from saved work state]

References: src/…/controller.ts• L157-170 src/…/controller.ts• L229-267

Conversation ownership

Each deferred save or clear belongs to the conversation that triggered it. A person-issued clear, resume, or new prompt can invalidate that pending action, so the controller does not apply an old reset to a new conversation state.

An aborted turn does not start or complete the flow. If a person sends a prompt before the pending clear runs, the controller waits for that turn and asks for a new save so the latest work is included.

References: src/…/controller.ts• L131-142 src/…/controller.ts• L174-187 src/…/controller.ts• L213-257

Host-hook integration

The host integration connects the policy controller to Claude Code's session, tool, turn, prompt, command, and UI events. It keeps the controller independent from host details while allowing automatic clearing to observe the main workflow and schedule host actions.

Event boundaries

The hook module creates one controller for the session. It observes tool results after the host processes them, tracks main-turn start and completion, and resets controller state when the conversation ends.

The host adapter supplies context usage, interactive-session status, prompt submission, /clear, user-labelled continuation, visible notes, and deferred work. Errors from the auto-clear path are contained so a tool call or turn can still complete normally.

References: src/…/mod-api.ts• L7-24 src/…/mod-api.ts• L26-67 src/…/register.ts• L26-57 src/…/register.ts• L103-141

Settings refresh

The hook rereads settings on a short time-to-live rather than on every tool call. A missing settings file uses defaults, while an unreadable or malformed existing file does not silently turn an earlier opt-out into an enabled policy.

This makes configuration changes take effect during a session without adding a file read to every event. The setting path also follows the configured claude-mem data directory so the hook and the rest of the product use the same policy source.

References: src/…/register.ts• L23-53 src/…/register.ts• L55-69 src/…/settings.ts• L80-103

Memory continuity

Automatic clearing depends on the work-state handoff rather than on copying the full old transcript into the new conversation. This keeps the reset focused on unfinished work while the wider capture and memory systems continue to observe normal events.

For the surrounding lifecycle, see capture and memory, hook event ingestion, transcript observation processing, and memory ingest and reinforcement. The reset also relates to the native memory bridge, remote worker capture, history and prompt import, and media artifact lifecycle.

Work-state handoff

The save request tells Claude to leave a compact record of the active task before the conversation is cleared. The continuation prompt then gives the fresh conversation a clear instruction to pick up that record instead of asking it to reconstruct the entire prior dialogue.

References: src/…/controller.ts• L271-299

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the enablement rule aligned with work-state availability. Automatic clearing must not create a reset path that has no usable handoff.
  • Keep threshold changes within the documented 1–95 percent range and preserve the default when input is invalid.
  • Preserve the distinction between main turns and subagent events. Counting subagents can trigger a reset while the main conversation is still usable.
  • Preserve conversation ownership checks around deferred prompts and clears. A delayed action must not affect a later user-issued clear or prompt.
  • Keep the host adapter's user-labelled continuation compatible with Claude Code versions that do not support asUser.

Important failure modes

TriggerConsequenceGuard
Work-state saving is disabled or the save does not succeedThe conversation is not cleared, so no work is lost through an incomplete handoffRequire both feature flags and verify the saved result before clearing
The user stops the save turnThe reset flow stops and waits for the next /clearTreat aborted turns as a deliberate stop
A user prompt starts before the deferred clearThe pending clear is delayed so the new turn is not omitted from the saved stateTrack the conversation and turn count
/clear failsThe old conversation remains active and the controller pauses automatic clearingReport the failure and wait for the next /clear
A fresh conversation starts at or above the thresholdRepeated clears could occur without useful contextDisable automatic clearing until restart

Key files

FileWhy to read it
src/…/controller.tsDefines the policy state machine, save handoff, reset sequence, and cancellation rules.
src/…/settings.tsDefines enablement, threshold limits, precedence, and settings paths.
src/…/register.tsShows how Claude Code events and host actions connect to the controller.
src/…/mod-api.tsDefines the host capabilities and event contracts used by the hook module.