Agent context engineering
Skill Lemirq/agent-best-practices/skills/agent-context-engineering
Guide context engineering for AI agents -- parallelization strategies, sharing context between subagents, avoiding context failure modes (poisoning, distraction, confusion, clash, rot), compressing context to prevent overflow, and feeding errors back into context for self-correction. Use when the user is building agent workflows that involve multiple steps, subagents, long-running tasks, or context window management. Also use when user mentions "context window", "context overflow", "agent context", "subagent communication", "context compression", "error handling in agents", or asks why their agent is degrading over long conversations.From its SKILL.md
npx -y skills add Lemirq/agent-best-practices --skill agent-context-engineeringAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
8.4 KB, as published. Nobody here has run it
Agent Context Engineering Patterns
Context engineering is both an art and a science. Give an agent too little context and it can't do its job. Give it too much or irrelevant context and it loses its way. These patterns help you provide just the right information at the right time.
Core Principle
Every token in the context influences the model's behavior, for better or worse. Context is not free -- even with million-token windows.
Pattern 5: Parallelize Carefully
Problem: Parallel workflows are fragile
When an agent breaks work into parallel subtasks, subagents working independently can create mutually incompatible outputs that the final agent must somehow combine.
Solution: Prefer single-threaded linear execution
For tasks with interdependencies, combine them into a single multiturn thread. This preserves continuous context in a more reliable architecture.
Instead of:
Task --> Agent splits --> Subagent 1 (parallel) + Subagent 2 (parallel) --> Agent combines
Prefer:
Task --> Agent breaks down --> Agent does subtask 1 --> Agent does subtask 2 --> Agent combines
(each step sees full context of prior steps)
When to parallelize
Only parallelize when subtasks are truly independent -- no shared state, no coordination needed. If there's any nuance where one subtask's output affects another, keep them sequential.
Example: Building a game
"Build a Temple Run clone" split into character movement (Subagent 1) and path generation (Subagent 2). Subagent 1 builds platformer-style controls with lethal enemies. Subagent 2 builds a branching path system requiring stopping and thinking. These are incompatible -- the final agent can't merge them.
Note: Different teams disagree here. Devin (Cognition) avoids parallelizing tasks. Claude Code relies heavily on parallelized tasks via subagents. Know your context.
Pattern 6: Share Context Between Subagents
Problem: Agent miscommunication
When a parent agent delegates to subagents, they can create mutually incompatible outputs -- like a manager splitting a task and getting conflicting results.
Solution: Ensure subagents share context
Instead of just "Do this specific task," ensure subagents can access shared context:
- Run in sequence so each subagent sees prior work
- Check output along the way before dispatching the next subagent
- Share the full trace, not just the action summary
Example: The red button
A user asks a vibe coding agent to build a website landing page.
- Without context engineering: Subagent A tells Subagent B "I made a red button." Subagent B has no idea why it's red.
- With context engineering: Subagent B sees Subagent A's full trace -- user request, brand color research, user approval. Now it understands why it's red and uses the same red for other elements.
Pattern 7: Avoid Context Failure Modes
Problem: Context isn't free
Even with large context windows, everything in context competes for the model's attention. There are five failure modes to watch for:
The Five Context Failure Modes
-
Context Poisoning
- A hallucination or error gets into context and is repeatedly referenced
- The agent treats it as ground truth and compounds the error
- Fix: Validate critical facts before they enter persistent context
-
Context Distraction
- Context becomes so long the model overfocuses on it and discounts its training data
- Fix: Keep context focused and relevant; prune aggressively
-
Context Confusion
- Irrelevant context is included, causing low-quality responses
- The model tries to use everything, even when it shouldn't
- Fix: Only include context directly relevant to the current step
-
Context Clash
- New information contradicts previous information in context
- The model doesn't know which to trust
- Fix: Resolve contradictions explicitly; don't just append updates
-
Context Rot
- Around 100K tokens, even large-context models start losing ability to discern important information from noise
- Fix: Compress context before hitting this threshold
Example: Pokemon agent benchmark
A Google Gemini team found performance degraded when prompts hit ~125K tokens (on a 500K window). They fixed it by:
- Using RAG to filter to top K results (not all results)
- Adding a context pruning tool to remove irrelevant information
- Storing structured context (goal, format, warnings, contextDump) assembled before each LLM call
Result: accuracy jumped from 34% to reliably over 90%.
Pattern 8: Compress Context
Problem: Context overflow
The naive approach of appending all context from every task eventually fills the window. Performance degrades, then the agent stops working.
Solution: Periodic context compression
Compress context between agent tasks using one or more strategies:
- Compress at every step -- summarize after each subtask
- Compress at threshold -- trigger when context reaches X% of window capacity
- Prune oldest context (hierarchical summarization)
- Recursive summarization -- chunk, summarize, combine, summarize again
- Post-process token-heavy tool calls (e.g., search results)
- Summarize at agent-agent boundaries -- reduce tokens during knowledge hand-off
Critical Warning
Summarization can lose important details. If specific events, decisions, or data points are crucial, identify them explicitly and do NOT compress those.
Real-world examples
- Claude Code: Runs autocompact at 95% capacity, summarizes the full trajectory. Supports manual compaction and custom instructions for what to preserve.
- Mastra: Provides composable memory processors --
TokenLimiter(removes oldest),ToolCallFilter(removes tool call messages). Custom logic viaMemoryProcessorclass.
Pattern 9: Feed Errors Into Context
Problem: LLM-generated code sometimes doesn't work
Agents run code while reasoning through problems. That code may fail.
Solution: Give the agent the error message
Feed the error message, the code, and relevant context back to the agent. The agent:
- Generates fixes
- Applies them
- Re-executes to verify the fix
- Repeats if needed
This creates resilient agents that self-correct instead of crashing.
Key Practice
If you notice commonly repeated error patterns, put them directly into your prompt. Don't make the agent rediscover the same fix every time.
Example
All major coding agents do this: Cursor's Auto Run mode captures errors and integrates them into context. Windsurf sends console errors to agent context. Replit Agent automates the diagnose-fix-re-execute loop.
Decision Framework
| Situation | Pattern to Apply |
|---|---|
| Subtasks have shared state or dependencies | Parallelize Carefully (go sequential) |
| Subagent outputs are inconsistent | Share Context Between Subagents |
| Agent produces random-seeming errors | Check for Context Failure Modes |
| Long-running tasks degrading | Compress Context |
| Agent-generated code fails | Feed Errors Into Context |
| Performance drops at ~100K+ tokens | Context Rot -- compress aggressively |
| Agent cites facts that seem wrong | Context Poisoning -- validate inputs |
Gotchas
- Large context windows don't solve context quality problems. 1M tokens doesn't mean "dump everything in."
- The structured context pattern (goal, returnFormat, warnings, contextDump) is a proven way to control what the model sees.
- Context compression can lose critical details. Explicitly protect important decisions and data.
- Error feeding works best with a retry limit -- don't let agents loop forever on the same error.
- When sharing context between subagents, share the reasoning trace, not just the output summary.
For detailed examples and implementation guidance, see references/context-patterns.md.