with one click
context-optimization
// [Utilities] Use when managing context window usage, compressing long sessions, or optimizing token usage.
// [Utilities] Use when managing context window usage, compressing long sessions, or optimizing token usage.
[HINT] Download the complete skill directory including SKILL.md and all related files
| name | context-optimization |
| version | 1.0.0 |
| description | [Utilities] Use when managing context window usage, compressing long sessions, or optimizing token usage. |
| disable-model-invocation | true |
Goal: Manage context window efficiently to maintain productivity in long Claude Code sessions.
Workflow:
Key Rules:
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Manage context window efficiently to maintain productivity in long sessions.
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Context Window (~200K tokens) ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā¤
ā System Prompt (CLAUDE.md excerpts) ~2,000 tokens ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā Working Memory (current task state) ~10,000 tokens ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā Retrieved Context (RAG from codebase) ~20,000 tokens ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā Episodic Memory (past session learnings) ~5,000 tokens ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā ā
ā Tool Descriptions (relevant tools only) ~3,000 tokens ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
Save critical findings to persistent memory:
// After discovering important patterns or decisions
mcp__memory__create_entities([
{
name: 'EmployeeValidation',
entityType: 'Pattern',
observations: ['Uses validation framework fluent API', 'Async validation via ValidateRequestAsync', 'Found in Application/UseCaseCommands/']
}
]);
When to Write:
Load relevant memories at session start:
// Search for relevant patterns
mcp__memory__search_nodes({ query: 'Employee validation pattern' });
// Open specific entities
mcp__memory__open_nodes({ names: ['EmployeeValidation', 'ServiceAModule'] });
When to Select:
Create context anchors every 10 operations:
=== CONTEXT ANCHOR ===
Current Task: Implement employee leave request feature
Completed:
- Created LeaveRequest entity with validation
- Added SaveLeaveRequestCommand with handler
- Implemented entity event handler for notifications
Remaining:
- Create GetLeaveRequestListQuery
- Add controller endpoint
- Write unit tests
Key Findings:
- Leave requests use service-specific repository
- Notifications via entity event handlers, not direct calls
- Validation uses validation framework fluent .AndAsync()
# Next Action: Create query handler with GetQueryBuilder pattern
Delegate specialized tasks to sub-agents:
// Explore codebase (reduced context)
Task({ subagent_type: 'Explore', prompt: 'Find all entity event handlers in the target service' });
// Plan implementation (focused context)
Task({ subagent_type: 'Plan', prompt: 'Plan leave request approval workflow' });
When to Isolate:
Every 10 operations, write a context anchor:
=== CONTEXT ANCHOR [10] ===
Task: [Original task description]
Phase: [Current phase number]
Progress: [What's been completed]
Findings: [Key discoveries]
Next: [Specific next step]
Confidence: [High/Medium/Low]
===========================
// ā Reading entire files
Read({ file_path: 'large-file.cs' });
// ā
Read specific sections
Read({ file_path: 'large-file.cs', offset: 100, limit: 50 });
// ā
Use grep to find specific content first
Grep({ pattern: 'class SaveEmployeeCommand', path: 'src/' });
// ā Multiple sequential searches
Grep({ pattern: 'CreateAsync' });
Grep({ pattern: 'UpdateAsync' });
Grep({ pattern: 'DeleteAsync' });
// ā
Combined pattern
Grep({ pattern: 'CreateAsync|UpdateAsync|DeleteAsync', output_mode: 'files_with_matches' });
// ā
Parallel reads for independent files
[Read({ file_path: 'file1.cs' }), Read({ file_path: 'file2.cs' }), Read({ file_path: 'file3.cs' })];
// Before ending session or hitting limits
const summary = {
task: 'Implementing employee leave request feature',
completed: ['Entity', 'Command', 'Handler'],
remaining: ['Query', 'Controller', 'Tests'],
discoveries: ['Use entity events for notifications'],
files: ['LeaveRequest.cs', 'SaveLeaveRequestCommand.cs']
};
// Save to memory
mcp__memory__create_entities([
{
name: `Session_${new Date().toISOString().split('T')[0]}`,
entityType: 'SessionSummary',
observations: [JSON.stringify(summary)]
}
]);
// At session start
mcp__memory__search_nodes({ query: 'Session leave request' });
| Anti-Pattern | Better Approach |
|---|---|
| Reading entire large files | Use offset/limit or grep first |
| Sequential searches | Combine with OR patterns |
| Repeating same searches | Cache results in memory |
| No context anchors | Write anchor every 10 ops |
| Not using sub-agents | Isolate exploration tasks |
| Forgetting discoveries | Save to memory entities |
Token Estimation:
Context Thresholds:
Memory Commands:
mcp__memory__create_entities - Save new knowledgemcp__memory__search_nodes - Find relevant contextmcp__memory__add_observations - Update existing entitiesmemory-management[IMPORTANT] Use
TaskCreateto break ALL work into small tasks BEFORE starting ā including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
AI Mistake Prevention ā Failure modes to avoid on every task:
Check downstream references before deleting. Deleting components causes documentation and code staleness cascades. Map all referencing files before removal. Verify AI-generated content against actual code. AI hallucinates APIs, class names, and method signatures. Always grep to confirm existence before documenting or referencing. Trace full dependency chain after edits. Changing a definition misses downstream variables and consumers derived from it. Always trace the full chain. Trace ALL code paths when verifying correctness. Confirming code exists is not confirming it executes. Always trace early exits, error branches, and conditional skips ā not just happy path. When debugging, ask "whose responsibility?" before fixing. Trace whether bug is in caller (wrong data) or callee (wrong handling). Fix at responsible layer ā never patch symptom site. Assume existing values are intentional ā ask WHY before changing. Before changing any constant, limit, flag, or pattern: read comments, check git blame, examine surrounding code. Verify ALL affected outputs, not just the first. Changes touching multiple stacks require verifying EVERY output. One green check is not all green checks. Holistic-first debugging ā resist nearest-attention trap. When investigating any failure, list EVERY precondition first (config, env vars, DB names, endpoints, DI registrations, data preconditions), then verify each against evidence before forming any code-layer hypothesis. Surgical changes ā apply the diff test. Bug fix: every changed line must trace directly to the bug. Don't restyle or improve adjacent code. Enhancement task: implement improvements AND announce them explicitly. Surface ambiguity before coding ā don't pick silently. If request has multiple interpretations, present each with effort estimate and ask. Never assume all-records, file-based, or more complex path.
Critical Thinking Mindset ā Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination: Never present guess as fact ā cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence ā certainty without evidence root of all hallucination.
MUST ATTENTION apply critical thinking ā every claim needs traced proof, confidence >80% to act. Anti-hallucination: never present guess as fact.
MUST ATTENTION apply AI mistake prevention ā holistic-first debugging, fix at responsible layer, surface ambiguity before coding, re-read files after compaction.
TaskCreate BEFORE startingfile:line evidence for every claim (confidence >80% to act)[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using TaskCreate.