context-degradation
Identifies and mitigates context degradation patterns like context poisoning or lost-in-middle issues to restore agent performance.
Install
mkdir -p .claude/skills/context-degradation && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/2183" && unzip -o skill.zip -d .claude/skills/context-degradation && rm skill.zipInstalls to .claude/skills/context-degradation
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
This skill should be used for diagnosing and mitigating context degradation: lost-in-middle failures, context poisoning, context clash, context confusion, attention-pattern issues, and agent performance degradation caused by accumulated or conflicting context.Key capabilities
- →Detects context clash and poisoning
- →Diagnoses attention-span failure patterns
- →Identifies lost-in-middle recall issues
- →Recommends context placement strategies
- →Analyzes agent performance drop-offs
How it works
Analyzes the conversation history against known attention U-curve models to pinpoint where context placement or accumulation causes recall failure.
Inputs & outputs
When to use context-degradation
- →Debug agent output failures
- →Resolve context-related performance drops
- →Optimize context for long conversations
About this skill
Context Degradation Patterns
Diagnose and fix context failures before they cascade. Context degradation is not binary — it is a continuum that manifests through five distinct, predictable patterns: lost-in-middle, poisoning, distraction, confusion, and clash. Each pattern has specific detection signals and mitigation strategies. Treat degradation as an engineering problem with measurable thresholds, not an unpredictable failure mode.
When to Activate
Activate this skill when:
- Agent performance degrades unexpectedly during long conversations
- Debugging cases where agents produce incorrect or irrelevant outputs
- Designing systems that must handle large contexts reliably
- Evaluating context engineering choices for production systems
- Investigating "lost in middle" phenomena in agent outputs
- Analyzing context-related failures in agent behavior
Do not activate this skill for adjacent work owned by other skills:
- Explaining foundational context mechanics without an active failure:
context-fundamentals. - Applying token-efficiency tactics after the failure pattern is known:
context-optimization. - Designing a compression or handoff summary strategy:
context-compression. - Persisting large outputs, logs, or scratch state outside the prompt:
filesystem-context.
Core Concepts
Structure context placement around the attention U-curve: beginning and end positions receive reliable attention, while middle positions suffer materially reduced recall accuracy in long-context experiments (claim-context-degradation-lost-middle-ruler). This is not a model bug but a consequence of attention mechanics — the first token (often BOS) acts as an "attention sink" that absorbs disproportionate attention budget, leaving middle tokens under-attended as context grows.
Treat context poisoning as a circuit breaker problem. Once a hallucination, tool error, or incorrect retrieved fact enters context, it compounds through repeated self-reference. A poisoned goals section causes every downstream decision to reinforce incorrect assumptions. Detection requires tracking claim provenance; recovery requires truncating to before the poisoning point or restarting with verified-only context.
Filter aggressively before loading context — even a single irrelevant document measurably degrades performance on relevant tasks. Models cannot "skip" irrelevant context; they must attend to everything provided, creating attention competition between relevant and irrelevant content. Move information that might be needed but is not immediately relevant behind tool calls instead of pre-loading it.
Isolate task contexts to prevent confusion. When context contains multiple task types or switches between objectives, models incorporate constraints from the wrong task, call tools appropriate for a different context, or blend requirements from multiple sources. Explicit task segmentation with separate context windows eliminates cross-contamination.
Resolve context clash through priority rules, not accumulation. When multiple correct-but-contradictory sources appear in context (version conflicts, perspective conflicts, multi-source retrieval), models cannot determine which applies. Mark contradictions explicitly, establish source precedence, and filter outdated versions before they enter context.
Detailed Topics
Lost-in-Middle: Detection and Placement Strategy
Place critical information at the beginning and end of context, never in the middle. The U-shaped attention curve means middle-positioned information suffers 10-40% reduced recall accuracy. For contexts over 4K tokens, this effect becomes significant.
Use summary structures that surface key findings at attention-favored positions. Add explicit section headers and structural markers — these help models navigate long contexts by creating attention anchors. When a document must be included in full, prepend a summary of its key points and append the critical conclusions.
Monitor for lost-in-middle symptoms: correct information exists in context but the model ignores it, responses contradict provided data, or the model "forgets" instructions given earlier in a long prompt.
Context Poisoning: Prevention and Recovery
Validate all external inputs before they enter context. Tool outputs, retrieved documents, and model-generated summaries are the three primary poisoning vectors. Each introduces unverified claims that subsequent reasoning treats as ground truth.
Detect poisoning through these signals: degraded output quality on previously-successful tasks, tool misalignment (wrong tools or parameters), and hallucinations that persist despite explicit correction. When these cluster, suspect poisoning rather than model capability issues.
Recover by removing poisoned content, not by adding corrections on top. Truncate to before the poisoning point, restart with clean context preserving only verified information, or explicitly mark the poisoned section and request re-evaluation from scratch. Layering corrections over poisoned context rarely works — the original errors retain attention weight.
Context Distraction: Curation Over Accumulation
Curate what enters context rather than relying on models to ignore irrelevant content. Research shows even a single distractor document triggers measurable performance degradation — the effect follows a step function, not a linear curve. Multiple distractors compound the problem.
Apply relevance filtering before loading retrieved documents. Use namespacing and structural organization to make section boundaries clear. Prefer tool-call-based access over pre-loading: store reference material behind retrieval tools so it enters context only when directly relevant to the current reasoning step.
Context Confusion: Task Isolation
Segment different tasks into separate context windows. Context confusion is distinct from distraction — it concerns the model applying wrong-context constraints to the current task, not just attention dilution. Signs include responses addressing the wrong aspect of a query, tool calls appropriate for a different task, and outputs mixing requirements from multiple sources.
Implement clear transitions between task contexts. Use state management that isolates objectives, constraints, and tool definitions per task. When task-switching within a single session is unavoidable, use explicit "context reset" markers that signal which constraints apply to the current segment.
Context Clash: Conflict Resolution Protocols
Establish source priority rules before conflicts arise. Context clash differs from poisoning — multiple pieces of information are individually correct but mutually contradictory (version conflicts, perspective differences, multi-source retrieval with divergent facts).
Implement version filtering to exclude outdated information before it enters context. When contradictions are unavoidable, mark them explicitly with structured conflict annotations: state what conflicts, which source each claim comes from, and which source takes precedence. Without explicit priority rules, models resolve contradictions unpredictably.
Empirical Benchmarks and Thresholds
Use these benchmarks to set design constraints — not as universal truths. RULER-style evidence shows advertised long-context support does not guarantee satisfactory task performance at that length (claim-context-degradation-lost-middle-ruler). Near-perfect needle-in-haystack scores do not predict real-world long-context performance.
Model-Specific Degradation Thresholds
Degradation onset varies significantly by model family and task type. As a general rule, expect degradation to begin at 60-70% of the advertised context window for complex retrieval tasks (RULER benchmark found only 50% of models claiming 32K+ context maintain satisfactory performance at that length). Key patterns:
- Models with extended thinking reduce hallucination through step-by-step verification but at higher latency and token cost
- Models optimized for agents/coding tend to have better attention management for tool-output-heavy contexts
- Models with very large context windows (1M+) handle more raw context but still follow U-shaped degradation curves — bigger windows do not eliminate the problem, they delay it
Always benchmark degradation thresholds with your specific workload rather than relying on published benchmarks. Model-specific thresholds go stale with each model update (see Gotcha 2).
Counterintuitive Findings
Account for these research-backed surprises when designing context strategies:
Shuffled context can outperform coherent context. Studies found incoherent (shuffled) haystacks can outperform logically ordered ones for some retrieval tasks (claim-context-degradation-distractor-shuffled). Coherent context may create false associations that confuse retrieval; incoherent context can force exact matching. Do not assume that better-organized context always yields better results — test both arrangements.
Single distractors have outsized impact. The performance hit from one irrelevant document is disproportionately large compared to adding more distractors after the first. Treat distractor prevention as binary: either keep context clean or accept significant degradation.
Low needle-question similarity accelerates degradation. Tasks requiring inference across dissimilar content degrade faster with context length than tasks with high surface-level similarity. Design retrieval to maximize semantic overlap between queries and retrieved content.
When Larger Contexts Hurt
Do not assume larger context windows improve performance. Performance remains stable up to a model-specific threshold, then degrades rapidly — the curve is non-linear with a cliff edge, not a gentle slope. For many models, meaningful degradation begins at 8K-16K tokens even when windows support much larger sizes.
Factor in cost: processing a 400K token context c
Content truncated.
When not to use it
- →Simple, short-context conversations
- →General performance debugging unrelated to context
Limitations
- →Diagnostic only; requires external optimization
- →Requires understanding of attention-span U-curves
How it compares
It treats context as an engineering constraint to be solved rather than a model hallucination issue.
Compared to similar skills
context-degradation side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| context-degradation (this skill) | 3 | 2mo | Review | Advanced |
| skill-creator | 128 | 3mo | Review | Advanced |
| skill-development | 17 | 8mo | Review | Intermediate |
| agent-identifier | 15 | 8mo | Review | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by muratcankoylan
View all by muratcankoylan →You might also like
skill-creator
anthropics
Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
skill-development
anthropics
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill content", or needs guidance on skill structure, progressive disclosure, or skill development best practices for Claude Code plugins.
agent-identifier
anthropics
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
llama-factory
zechenzhangAGI
Expert guidance for fine-tuning LLMs with LLaMA-Factory - WebUI no-code, 100+ models, 2/3/4/5/6/8-bit QLoRA, multimodal support
dify-dsl-generator
wwwzhouhui
专业的 Dify 工作流 DSL/YML 文件生成器,根据用户业务需求自动生成完整的 Dify 工作流配置文件,支持各种节点类型和复杂工作流逻辑
memory-mcp
d-o-hub
Use and troubleshoot the Memory MCP server for episodic memory retrieval and pattern analysis. Use this skill when working with MCP server tools (query_memory, analyze_patterns, advanced_pattern_analysis), validating the MCP implementation, or debugging MCP server issues.