# Claude Code Context Management: Architectural Alternatives to /compact and /clear

> Discover architectural alternatives to Claude Code's /compact and /clear commands. Learn to manage sessions declaratively with isolated contexts and persistent memory for efficient Claude Code interactions.

- Repository: [Shayan Rais/claude-code-best-practice](https://github.com/shanraisshan/claude-code-best-practice)
- Tags: architecture
- Published: 2026-03-12

---

**Use declarative agent orchestration with isolated contexts and persistent memory to manage Claude Code sessions without manual `/compact` or `/clear` interventions.**

The **claude-code-best-practice** repository demonstrates how to handle context limits and session resets through structural workflow design rather than reactive commands. By leveraging the **Command → Agent → Skill** architecture with explicit context isolation, you can programmatically enforce the boundaries that `/compact` and `/clear` address manually.

---

## Why Manual Context Management Falls Short

Running complex multi-step workflows in Claude Code naturally consumes context window capacity. While built-in commands like `/compact` (summarizing at 50% usage) and `/clear` (wiping the session) provide emergency relief, they interrupt workflow state and require manual intervention. The **shanraisshan/claude-code-best-practice** reference implementation eliminates this friction by architecting workflows where context boundaries are enforced declaratively through agent definitions and memory scopes.

---

## Handling the 50% Threshold: Agent Context Limits

Instead of waiting for manual compaction at 50% context usage, define agents with strict **turn limits** that automatically bound context growth. In [`.claude/agents/weather-agent.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/agents/weather-agent.md), the repository demonstrates this pattern:

```yaml
---
name: weather-agent
description: Fetches weather data with bounded context
tools: Read, Bash
model: sonnet
maxTurns: 3
permissionMode: acceptEdits
memory: project
skills:
  - weather-fetcher
---

```

**Key mechanism:** The `maxTurns: 3` parameter acts as a hard limit on conversation length, preventing the gradual accumulation of token usage that would otherwise trigger the need for `/compact`. When the agent reaches its turn limit, it returns control to the orchestrating command with a clean summary, effectively compressing context automatically.

The **Task** tool invocation in [`.claude/commands/weather-orchestrator.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/commands/weather-orchestrator.md) spawns this isolated agent:

```yaml
- tool: Task
  args:
    agent: weather-agent
    prompt: "Fetch the current temperature for {{location}}"

```

This pattern creates a **context boundary**—the agent operates in a sandboxed context that terminates after three turns, returning only the essential results (temperature data) rather than carrying forward the full conversation history.

---

## Mid-Session Resets: Isolated Contexts vs. /clear

The `/clear` command wipes the entire session state, forcing you to rebuild context. The repository’s orchestration workflow achieves cleaner mid-session resets by spawning **disposable agent contexts** that terminate naturally after completing their function.

### The Reset Pattern

1. **Pre-reset:** The main command holds high-level orchestration state in [`CLAUDE.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/CLAUDE.md) or project memory.
2. **Execution:** A specialized agent (e.g., `weather-agent`) is spawned via the **Task** tool with its own isolated context.
3. **Post-reset:** Upon completion or maxTurns exhaustion, the agent context collapses, returning only structured output.

This architectural `/clear` alternative preserves your orchestration state while dumping the temporary working context. The `weather-orchestrator` command demonstrates this in [`.claude/commands/weather-orchestrator.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/commands/weather-orchestrator.md) by chaining agents and skills without polluting the parent context:

```yaml
- tool: Task
  args:
    agent: weather-agent
    # Agent context isolated here

    
- tool: Skill
  args:
    skill: weather-svg-creator
    # Fresh context for SVG generation

```

Each tool invocation effectively resets the working context while the orchestration state persists in the command’s YAML-defined workflow.

---

## Persistent Memory Beyond Session Resets

While `/clear` wipes transient session data, the repository’s **Memory** system ensures critical instructions survive resets. The [`CLAUDE.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/CLAUDE.md) file at the repository root and rule files in `.claude/rules/` define **project-level persistent memory** that reloads automatically when Claude Code restarts or contexts switch.

### Memory Scopes in Practice

- **Project memory:** Defined in [`CLAUDE.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/CLAUDE.md), available to all agents spawned in the repository.
- **Agent-specific memory:** Set via `memory: project` in agent YAML front-matter to ensure consistency across sub-sessions.
- **Skill-level context:** Skills in `.claude/skills/<name>/SKILL.md` carry their own isolated instructions, acting as compact, reusable context blocks.

This hierarchy means you can "clear" working contexts aggressively (via agent termination) without losing architectural knowledge, essentially achieving the cleanliness of `/clear` with the persistence of a saved session.

---

## Implementation: Weather Orchestrator Workflow

The canonical example in [`orchestration-workflow/orchestration-workflow.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/orchestration-workflow/orchestration-workflow.md) demonstrates complete context lifecycle management:

1. **Command entry** (`/weather-orchestrator`) initializes with minimal context.
2. **Agent isolation** spawns `weather-agent` with `maxTurns: 3`, preventing context bloat during API calls.
3. **Skill invocation** via `weather-svg-creator` operates in yet another isolated context for file generation.
4. **Hooks** in [`.claude/hooks/scripts/hooks.py`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/hooks/scripts/hooks.py) execute cleanup or logging at `PreToolUse` and `PostToolUse` lifecycle events, providing deterministic reset behavior:

```yaml
hooks:
  PreToolUse:
    - matcher: ".*"
      hooks:
        - type: command
          command: python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/scripts/hooks.py
          timeout: 5000
          async: true

```

These hooks function as automated **pre-compact** triggers, allowing you to log, summarize, or archive context before it grows unwieldy.

---

## Summary

- **Bounded agents** with `maxTurns` enforce context limits proactively, eliminating the need for reactive `/compact` calls at 50% usage.
- **Task tool orchestration** creates isolated sub-contexts that act as programmatic `/clear` operations, dumping temporary state while preserving orchestration logic.
- **Persistent memory** via [`CLAUDE.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/CLAUDE.md) and project-scoped rules ensures critical instructions survive aggressive context resets.
- **Lifecycle hooks** provide deterministic intervention points for context management scripts before tools execute.

---

## Frequently Asked Questions

### How does maxTurns compare to manually running /compact?

The `maxTurns` parameter in agent definitions (as shown in [`.claude/agents/weather-agent.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/agents/weather-agent.md)) acts as a preventive boundary rather than a reactive compression. While `/compact` summarizes existing context when you hit 50% usage, `maxTurns: 3` terminates the agent conversation before exponential context growth occurs, returning only the final result to the parent orchestrator.

### Can I use /clear within an agent workflow?

No, agents operate in isolated contexts that terminate naturally after `maxTurns` or task completion. This architectural isolation achieves what `/clear` does manually—wiping temporary working memory—without requiring user intervention. The parent command context remains intact, unlike global `/clear` which affects the entire session.

### Where should I store context that must survive agent resets?

Store persistent instructions in [`CLAUDE.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/CLAUDE.md) (repository root) or define project-level rules in `.claude/rules/`. According to the repository’s [`.claude/settings.json`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/.claude/settings.json) and memory architecture, these files reload automatically across session boundaries and agent spawns, ensuring continuity even when individual agent contexts are cleared.

### Do hooks run when I spawn a new agent?

Yes. Hooks defined in `.claude/hooks/` and attached to agents (like the `PreToolUse` hook in [`weather-agent.md`](https://github.com/shanraisshan/claude-code-best-practice/blob/main/weather-agent.md)) execute on lifecycle events within that agent’s context. This allows you to trigger logging, validation, or context-summarization scripts automatically whenever the agent uses a tool, providing fine-grained control over context growth without manual `/compact` commands.