You are setting up a context management layer for a Claude Code project. Generate the following 4 files exactly as specified, then explain how to use them.
---
description: Audit current context usage across active agents and subagents
---
Analyze the current project's context allocation:
1. **Check current usage**: Run the `/cost` command or check the status bar to understand current token consumption.
2. **Inventory agent profiles**: List all `.claude/agents/*.md` files and categorize each:
- **Advisory** (read-only analysis): agents that only read code — architect, security, analyst, validator
- **Executor** (read-write): agents that modify files — developer, frontend, devops
3. **Estimate context cost per agent**: For each agent profile:
- Count the lines in the profile itself (each line ≈ 4 tokens)
- Identify which files/globs the agent typically loads based on its instructions
- Flag agents that load broad patterns (e.g., `**/*.ts`) vs scoped ones (e.g., `src/auth/*.ts`)
4. **Output a context budget table**:
| Agent | Type | Profile Size (lines) | Typical File Load | Risk |
|-------|------|---------------------|-------------------|------|
| architect | advisory | ~80 | broad (reads whole modules) | medium |
| developer | executor | ~60 | scoped (specific files) | low |
| ... | ... | ... | ... | ... |
Risk levels:
- **Low**: Agent loads < 20 files, scoped globs
- **Medium**: Agent loads 20-50 files or uses moderate globs
- **High**: Agent loads 50+ files or uses `**/*` patterns
5. **Recommend execution mode per agent**:
- Agents with **low** context needs → spawn as **subagent** (Task tool with focused prompt)
- Agents with **high** context needs or needing sustained reasoning → spawn as **Agent Teams member** (TeamCreate + Task with team_name)
- Agents that need to debate or exchange findings → **Agent Teams** (they need SendMessage)
6. **Suggest optimizations**:
- Which agent profiles should add file scope restrictions
- Which agents are loading redundant files
- Whether any agents should be merged or split---
description: Build a clean handoff payload and dispatch a focused subagent
---
Before spawning a subagent via the Task tool, build a minimal handoff payload. This prevents context pollution in the parent session.
**Step 1 — Extract the task spec** from the current conversation:
- What needs to be done (1-3 sentences, imperative voice)
- Input files (exact paths, not globs — e.g., `src/auth/login.ts` not `src/auth/*`)
- Expected output (file path + format)
- Constraints (what NOT to modify, what tests must pass)
**Step 2 — Strip reasoning traces**: The subagent does NOT need to know:
- What approaches you considered and rejected
- Why you chose this approach over alternatives
- Your exploration history or debugging journey
Only pass: conclusions, decisions, and the specific spec.
**Step 3 — Build the payload** as a structured prompt for the Task tool:
```
Task: [1-3 sentence description of what to build/fix/analyze]
Input files:
- path/to/file1.ts
- path/to/file2.ts
Expected output:
- path/to/output.ts (new file with X interface)
- OR: modifications to path/to/existing.ts
Constraints:
- Do not modify path/to/protected.ts
- Must pass: npm test -- --grep "auth"
- Follow existing patterns in src/auth/
Context (decisions only):
- We chose JWT over session cookies (see ADR-012)
- The auth middleware must run before route handlers
```
**Step 4 — Select model tier**:
| Task Scope | Model | Subagent Type | When |
|-----------|-------|---------------|------|
| < 50 lines of change | haiku | Task(model="haiku") | Simple edits, formatting, boilerplate |
| 50-500 lines | sonnet | Task(model="sonnet") | Feature implementation, refactoring |
| Architectural judgment needed | opus | Promote to Agent Teams | Design decisions, complex debugging |
| Read-only analysis | haiku | Task(subagent_type="Explore") | Codebase search, pattern finding |
**Step 5 — Dispatch**: Use the Task tool with the payload as the prompt. Set `subagent_type` to `general-purpose` for implementation tasks or `Explore` for read-only research.
Do NOT pass the full conversation history. The payload IS the prompt.---
description: Checkpoint session state and clean context when usage is high
---
Run this when your session is getting long or you notice degraded responses.
**Step 1 — Check current usage**: Note the token count from the status bar or `/cost` output.
**Step 2 — Assess**:
- If below 60% of 200K (< 120K tokens used): report status, no action needed.
- If between 60-80%: create checkpoint, continue in current session.
- If above 80%: create checkpoint, recommend starting a fresh session.
**Step 3 — Create checkpoint**: Write a structured summary of the current session:
```
## Session Checkpoint — [date]
### Completed
- [bullet point per completed task with file paths]
### Modified Files
- `path/to/file.ts` — added auth middleware
- `path/to/test.ts` — new test for login flow
### Pending Tasks
- [ ] Wire auth into API routes
- [ ] Add error handling for expired tokens
### Active Decisions (must carry forward)
- Using JWT with 15-minute expiry (ADR-012)
- Auth middleware runs before all /api/* routes
- Test database uses SQLite in-memory
### Context Usage
- Estimated: [X]K / 200K tokens ([Y]%)
```
**Step 4 — Recommend action**:
| Usage | Action |
|-------|--------|
| < 60% | Continue working. No cleanup needed. |
| 60-80% | Consider using `/compact` to compress context. Checkpoint saved above as fallback. |
| > 80% | Start a fresh session. Paste the checkpoint above as your opening message. |
**Step 5 — If starting fresh**: Copy the checkpoint and paste it into a new Claude Code session. The new session starts with full context of what was done and what remains, without the accumulated tool outputs and exploration that filled the original context.# Context Management Rules
All agents in this project follow these context discipline rules.
## File Loading
- **Scope aggressively**: Never glob entire directories (`**/*.ts`). Always scope to specific subdirectories or file patterns (`src/auth/**/*.ts`).
- **Check before loading**: Before reading a file, check if the information is already available from a previous tool call in this session.
- **Use line ranges**: Prefer reading specific line ranges over full files when you only need a section. Use the `offset` and `limit` parameters on the Read tool.
- **Prefer Grep over Read**: When looking for specific patterns, use Grep to find relevant files first, then read only the matches.
## Subagent Handoffs
- When dispatching to a subagent, follow the `/dispatch-subagent` format.
- **Never forward full conversation history** to subagents. Build a focused payload.
- **Strip reasoning traces**: Send conclusions and decisions, not the thought process that produced them. The subagent doesn't need to know what you tried and rejected.
- **Specify exact files**: Pass file paths, not directory globs. The subagent should read only what it needs.
## Session Hygiene
- Monitor context usage throughout the session.
- When approaching 60% usage, run `/context-clean` to checkpoint.
- Advisory agents (read-only) should complete and return results promptly — don't hold context open for analysis you've already finished.
- Executor agents working on multi-file changes should checkpoint after each logical unit of work.
## Budget Guidelines
These are target budgets per dispatch. Exceeding them means the task should be restructured.
| Role | Target Budget | Rationale |
|------|--------------|-----------|
| Advisory agents (analyst, security) | < 30K tokens | Read-only analysis, no file editing overhead |
| Executor agents (developer, frontend) | < 80K tokens | Need room for file reads + edits + test output |
| Orchestrator / parent session | Reserve 40K tokens | Must retain capacity for final synthesis and decisions |
## Agent Teams vs Subagents — When to Use Which
| Use Agent Teams when... | Use Subagents when... |
|------------------------|----------------------|
| Agents need to debate or exchange findings | Task is self-contained with clear input/output |
| Multiple agents work on interconnected files | Agent works on independent files |
| Sustained reasoning across multiple turns | Single-turn: do task, return result |
| You need 3 or more perspectives on the same code | You need one agent to do one focused job |
Agent Teams = parallel processes with shared filesystem (expensive, powerful).
Subagents = function calls with own stack (cheap, focused).
In practice: use Agent Teams for the outer loop, subagents for inner tasks each team member dispatches.- Confirm all 4 files were created with the correct paths
- Show the directory structure under
.claude/:.claude/ ├── agents/ │ ├── context-rules.md ← NEW: shared budget rules │ └── [your-agents].md └── commands/ ├── context-audit.md ← NEW: map context cost ├── context-clean.md ← NEW: checkpoint + cleanup ├── dispatch-subagent.md ← NEW: clean handoff builder └── [your-commands].md - Explain the workflow:
- Start with
/context-auditto understand your current context allocation across agents - Use
/dispatch-subagentbefore spawning any focused task — it builds clean payloads - Run
/context-cleanwhen sessions get long — checkpoints state for fresh sessions - All agents automatically load
context-rules.mdfor shared discipline (place it in.claude/agents/so Agent Teams members see it)
- Start with
- Context budget reference: Default is 200K tokens per Claude Code session. Plan all budgets around this limit.