context-optimization
Skill18k starsChanged 4 months agoMITView on GitHub
This skill should be used for improving context efficiency: context budgeting, observation masking, prefix or KV-cache strategy, partitioning, token-cost reduction, retrieval scoping, and extending effective context capacity without lowering answer quality.
14 other projects use a version of this, 10 of them edited.
Trending
More talk lately.about the whole repository
Most recently taken up by
- AbdullahMalik17/Digital-FTEedited, first seen Sep 26, 2026
- SkotAlexsander/skillsedited, first seen Sep 16, 2026
- docxology/templateedited, first seen Aug 29, 2026
- VoDaiLocz/kilo-kit-mcptheir own version, first seen Aug 21, 2026
- Fandry96/k3-agentic-skillsedited, first seen May 12, 2026
- JubaKitiashvili/context-memtheir own version, first seen Apr 17, 2026
Who's talking about muratcankoylan/Agent-Skills-for-Context-Engineering
- @dailygithubtrends.bsky.social“今日のGitHubトレンド muratcankoylan/Agent-Skills-for-Context-Engineering …”Bluesky · Feb 27, 2026 · 3 likes
- A Hacker News story“Agent-Skills-for-Context-Engineering”Hacker News · Dec 25, 2025 · 3 points
- A Hacker News story“Agent Skills for Context Engineering”Hacker News · Dec 22, 2025 · 3 points
- AAswordman/OperitSkillMarket“memory-systems”GitHub · Feb 20, 2026 · 2 reactions
- vercel-labs/skills“[Bug]: Only some skills discovered from repositories with nested skills/ directory structure”GitHub · Jan 21, 2026 · 2 reactions
The biggest 5 of 44 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 44
Talked about on GitHub, Bluesky and Hacker News (44 times).
On GitHub · 37
- Feb 20, 2026memory-systems — AAswordman/OperitSkillMarket2 reactions
- Jan 21, 2026[Bug]: Only some skills discovered from repositories with nested skills/ directory structure — vercel-labs/skills2 reactions · 6 comments
- Aug 2, 2026Add more skills from below repos https://github.com/nextlevelbuilder/ui-ux-pro-max-skill https://github.com/hardikpandya/stop-slop https://github.com/muratcankoylan/agent-skills-for-context-engineering — shivam-verma-philips-1/ai-team1 reaction
- Mar 22, 2026More context engineering — davidamitchell/Research1 reaction
- Dec 25, 2025Add skills: muratcankoylan/context-engineering collection — VoltAgent/awesome-agent-skills1 reaction
32 more on GitHub
- Oct 28, 2026docs(compound-packs): add ci-compound-pack for runner placement, efficient CI and check verdicts — systemfsoftware/systemfsoftware0 reactions · 1 comment
- Oct 9, 2026[Candidate] muratcankoylan/agent-skills-for-context-engineering/skills/context-fundamentals - context-fundamentals — ProSkillsMD/proskills0 reactions · 1 comment
- Oct 9, 2026[Candidate] muratcankoylan/agent-skills-for-context-engineering/skills/context-degradation - context-degradation — ProSkillsMD/proskills0 reactions · 1 comment
- Oct 9, 2026[Candidate] muratcankoylan/agent-skills-for-context-engineering/skills/context-compression - context-compression — ProSkillsMD/proskills0 reactions · 1 comment
- Oct 4, 2026claude-code-plugins.github.muratcankoylan.agent-skills-for-context-engineering: init at 2.3.0 — sudosubin/agents.nix0 reactions
- Oct 4, 2026claude-code-marketplaces.github.muratcankoylan.agent-skills-for-context-engineering: init at 2.3.0 — sudosubin/agents.nix0 reactions
- Oct 3, 2026Skills: vendor the BADF-compatible subset of Agent-Skills-for-Context-Engineering at IMPLEMENTED (pinned, overlaid, not routed) — bstBizEra/badf0 reactions
- Sep 30, 2026agent-skills.github.muratcankoylan.agent-skills-for-context-engineering: init at 2.3.0 — sudosubin/agents.nix0 reactions
- Jul 9, 2026[Collection]: muratcankoylan/agent-skills-for-context-engineering — shimoncohen/the-great-skill-dictionary0 reactions · 2 comments
- May 30, 2026feat(swarm): latent-briefing — KV cache compaction as orchestrator-to-worker context handoff — deftai/directive0 reactions
- Apr 25, 2026Audit candidate: muratcankoylan/Agent-Skills-for-Context-Engineering — xiaolai/nlpm0 reactions · 3 comments
- Mar 24, 2026Dynamic skill loading — install new tools at runtime without restarting — JeetVaidya1/jarvis0 reactions
- Mar 22, 2026Research: Applied context engineering — practical skills, workflows, and best practices for agent development — davidamitchell/Research0 reactions
- Mar 22, 2026research: 外部AI知見(Claude Skills / MCP / OSS)の分析と活用計画 — uminomae/creation-space0 reactions · 2 comments
- Mar 8, 2026Research: Context Engines for AI Agents — Market Analysis, Comparison & Context vs Memory — humanjack/ai-engineering0 reactions
- Feb 27, 2026Agent Skills for Context Engineering — MateuszNaKodach/SelfImprovement0 reactions
- Feb 26, 2026Research: Agent Skill Systems — Standards, Protocols & Frameworks for Extending AI Agents — humanjack/ai-engineering0 reactions
- Feb 25, 2026Analysis: Agent-Skills-for-Context-Engineering — Context Management Patterns for AI Agents — humanjack/ai-engineering0 reactions
- Feb 20, 2026tool-design — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026multi-agent-patterns — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026evaluation — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026context-optimization — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026context-fundamentals — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026context-degradation — AAswordman/OperitSkillMarket0 reactions
- Feb 20, 2026context-compression — AAswordman/OperitSkillMarket0 reactions
- Jan 6, 2026New plugins: 11 skills from skills (low risk) — aiskillstore/marketplace0 reactions
- Jan 3, 2026Weekly Journal Sources - Week of 2026-01-06 — beijaflor/gen-ai-journal0 reactions · 1 comment
- Dec 27, 2025Multi cli integration — AutoMaker-Org/automaker0 reactions · 3 comments
- Dec 25, 2025Enhance skills with Agent-Skills repository patterns — jamditis/tools0 reactions
- Dec 24, 2025Agent-Skills-for-Context-Engineering — jonath92/Copilot-Training0 reactions
- Dec 22, 2025Integrate Tool Use Learning — m2ux/concept-rag0 reactions
- Dec 12, 2025dec 2025 jan 2026 — kimtth/azure-openai-llm-notes0 reactions
On Bluesky · 5
- Feb 27, 2026今日のGitHubトレンド muratcankoylan/Agent-Skills-for-Context-Engineering このリポジトリは、AIエージェントの性能を最大化するための「コンテキストエンジニアリング」に焦点を当てたスキル集です。… — @dailygithubtrends.bsky.social3 likes and reposts
- May 27, 2026https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering — @sigmanor.net1 likes and repost
- Feb 27, 2026🎉 Celebrating! 🎉 (500+ new stars) 📦 muratcankoylan / Agent-Skills-for-Context-Engineering ⭐ 12,191 (+836) 🗒 Python A comprehensive… — @github-trending.bsky.social1 likes and repost · 1 reply
- Feb 26, 2026github.com/muratcankoyl... — @pcl25387.bsky.social1 likes and repost
- Feb 25, 2026今日のGitHubトレンド muratcankoylan/Agent-Skills-for-Context-Engineering このリポジトリは、AIエージェントの性能を最大化するための「コンテキストエンジニアリング」に焦点を当てたスキル集です。… — @dailygithubtrends.bsky.social1 likes and repost
On Hacker News · 2
- Dec 25, 2025Agent-Skills-for-Context-Engineering3 points
- Dec 22, 2025Agent Skills for Context Engineering3 points · 3 comments
Used with
Projects with it also use configuring-dapr-pubsub, containerizing-applications and 7 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
AbdullahMalik17Skillconfiguring-dapr-pubsub
Configures Dapr pub/sub components for event-driven microservices with Kafka or Redis. Use when wiring agent-to-agent communication, setting up event subscriptions, or integrating Dapr sidecars. Covers component configuration, subscription patterns, publishing events, and Kubernetes deployment. NOT when using direct Kafka clients or non-Dapr messaging patterns.
Also in 3 projects that use this
AbdullahMalik17Skillcontainerizing-applications
Containerizes applications with Docker, docker-compose, and Helm charts. Use when creating Dockerfiles, docker-compose configurations, or Helm charts for Kubernetes. Includes Docker Hardened Images (95% fewer CVEs), multi-stage builds, and 15+ battle-tested gotchas.
Also in 3 projects that use this
xfstudioSkillconversation-memory
Persistent memory systems for LLM conversations including short-term, long-term, and entity-based memory Use when: conversation memory, remember, memory persistence, long-term memory, chat history.
Also in 3 projects that use this
- +6 more from AbdullahMalik17
Other versions14 projects use a version of this.
Word for word · 0
None found.
Edited · 10
- Fandry96/k3-agentic-skills★ 2720% same
- docxology/template★ 2099% same
- AbdullahMalik17/Digital-FTE★ 1220% same
- AbdullahMalik17/Hacathan_5★ 920% same
- AbdullahMalik17/My_skills★ 920% same
- xfstudio/skills★ 920% same
- rohunvora/my-claude-skills★ 620% same
- ai4brands-design/claude-skills★ 220% same
- goodnessibeh/ai-dev-boilerplate★ 192% same
- SkotAlexsander/skills★ 199% same
Wrote their own version · 4
- VoDaiLocz/kilo-kit-mcp★ 27same name
- JubaKitiashvili/context-mem★ 19same name
- VersoXBT/claude-initial-setup★ 4same name
- Downey6689/skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository21 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- context-engineering-collectionSkill
- advanced-evaluationSkill
- bdi-mental-statesSkill
- context-compressionSkill
- context-degradationSkill
- context-fundamentalsSkill
- evaluationSkill
- filesystem-contextSkill
- harness-engineeringSkill
- hosted-agentsSkill
- latent-briefingSkill
- long-horizon-promptingSkill
- memory-systemsSkill
- multi-agent-patternsSkill
- project-developmentSkill
- self-improvement-loopsSkill
- self-managed-contextSkill
- tool-designSkill
- skill-templateSkill
The file
We split this skill into the rules it gives an agent
4 rules. 1 is common, 3 are distinctive, and 0 are very specific to this project.
1
Common
Most of the 13 edited versions we read keep these.
3
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 20
Do not activate this skill for adjacent work owned by other skills:
- Distinctive: line 51
Retrieved documents: Keep claims, facts, and data points relevant to the active task.
- Distinctive: line 92
Use trigger-based optimization rather than periodic optimization.
- Common: line 166
Test optimization at production scale
“Common” is measured: kept by at least 6 in 10 of the 13 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Context Optimization Techniques
Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. Effective optimization increases useful capacity without requiring larger models or longer windows — but only when applied with measurement discipline. The techniques below are ordered by impact and risk.
When to Activate
Activate this skill when:
- Context budgets or token costs constrain task complexity
- Observation masking can replace verbose tool outputs with retrievable references
- Prefix or KV-cache hit rate needs improvement
- Retrieval scoping can reduce irrelevant loaded context
- Context partitioning can extend effective capacity across agents
- Budget triggers are needed for masking, compaction, or partitioning
Do not activate this skill for adjacent work owned by other skills:
- Explaining why attention or context windows behave this way:
context-fundamentals. - Diagnosing active lost-in-middle, poisoning, distraction, confusion, or clash:
context-degradation. - Designing a structured handoff summary for a long conversation:
context-compression. - Storing large outputs, plans, or logs as files:
filesystem-context. - Model-initiated rewrites of its own context and their re-prefill cost:
self-managed-context.
Core Concepts
Apply four primary strategies in this priority order:
- KV-cache optimization — Reorder and stabilize prompt structure so the inference engine reuses cached Key/Value tensors. This is the cheapest optimization when the runtime supports prefix caching: low quality risk, immediate cost and latency savings. Apply it first when stable prefixes exist.
- Observation masking — Replace verbose tool outputs with compact references once their purpose has been served. Tool outputs can dominate agent trajectories (claim-context-optimization-tool-output-dominance), so masking often yields the largest capacity gains. The original content remains retrievable if needed downstream.
- Compaction — Summarize accumulated context when utilization exceeds 70%, then reinitialize with the summary. This distills the window's contents while preserving task-critical state. Compaction is lossy — apply it after masking has already removed the low-value bulk.
- Context partitioning — Split work across sub-agents with isolated contexts when a single window cannot hold the full problem. Each sub-agent operates in a clean context focused on its subtask. Reserve this for tasks where estimated context exceeds 60% of the window limit, because coordination overhead is real.
The governing principle: context quality matters more than quantity. Every optimization preserves signal while reducing noise. Measure before optimizing, then measure the optimization's effect.
Detailed Topics
Compaction Strategies
Trigger compaction when context utilization exceeds 70%: summarize the current context, then reinitialize with the summary. This distills the window's contents in a high-fidelity manner, enabling continuation with minimal performance degradation. Prioritize compressing tool outputs first (they consume 80%+ of tokens), then old conversation turns, then retrieved documents. Never compress the system prompt — it anchors model behavior and its removal causes unpredictable degradation.
Preserve different elements by message type:
- Tool outputs: Extract key findings, metrics, error codes, and conclusions. Strip verbose raw output, stack traces (unless debugging is ongoing), and boilerplate headers.
- Conversational turns: Retain decisions, commitments, user preferences, and context shifts. Remove filler, pleasantries, and exploratory back-and-forth that led to a conclusion already captured.
- Retrieved documents: Keep claims, facts, and data points relevant to the active task. Remove supporting evidence and elaboration that served a one-time reasoning purpose.
Target 50-70% token reduction with less than 5% quality degradation. If compaction exceeds 70% reduction, audit the summary for critical information loss — over-aggressive compaction is the most common failure mode.
Observation Masking
Mask observations selectively based on recency and ongoing relevance — not uniformly. Apply these rules:
- Never mask: Observations critical to the current task, observations from the most recent turn, observations used in active reasoning chains, and error outputs when debugging is in progress.
- Mask after 3+ turns: Verbose outputs whose key points have already been extracted into the conversation flow. Replace with a compact reference:
[Obs:{ref_id} elided. Key: {summary}. Full content retrievable.] - Always mask immediately: Repeated/duplicate outputs, boilerplate headers and footers, outputs already summarized earlier in the conversation.
Masking should achieve 60-80% reduction in masked observations with less than 2% quality impact. The key is maintaining retrievability — store the full content externally and keep the reference ID in context so the agent can request the original if needed.
KV-Cache Optimization
Maximize prefix cache hits by structuring prompts so that stable content occupies the prefix and dynamic content appears at the end. KV-cache stores Key and Value tensors computed during inference; when consecutive requests share an identical prefix, the cached tensors are reused, saving both cost and latency.
Apply this ordering in every prompt:
- System prompt (most stable — never changes within a session)
- Tool definitions (stable across requests)
- Frequently reused templates and few-shot examples
- Conversation history (grows but shares prefix with prior turns)
- Current query and dynamic content (least stable — always last)
Design prompts for cache stability: remove timestamps, session counters, and request IDs from the system prompt. Move dynamic metadata into a separate user message or tool result where it does not break the prefix. Even a single whitespace change in the prefix invalidates the entire cached block downstream of that change. The same rule prices any compaction or masking edit applied to earlier history: its cost is the text that follows it, so batch such edits and prefer them near the end of the context.
Target 70%+ cache hit rate for stable workloads. At scale, this translates to 50%+ cost reduction and 40%+ latency reduction on cached tokens.
Context Partitioning
Partition work across sub-agents when a single context cannot hold the full problem without triggering aggressive compaction. Each sub-agent operates in a clean, focused context for its subtask, then returns a structured result to a coordinator agent.
Plan partitioning when estimated task context exceeds 60% of the window limit. Decompose the task into independent subtasks, assign each to a sub-agent, and aggregate results. Validate that all partitions completed before merging, merge compatible results, and apply summarization if the aggregated output still exceeds budget.
This approach achieves separation of concerns — detailed search context stays isolated within sub-agents while the coordinator focuses on synthesis. However, coordination has real token cost: the coordinator prompt, result aggregation, and error handling all consume tokens. Only partition when the savings exceed this overhead.
Budget Management
Allocate explicit token budgets across context categories before the session begins: system prompt, tool definitions, retrieved documents, message history, tool outputs, and a reserved buffer (5-10% of total). Monitor usage against budget continuously and trigger optimization when any category exceeds its allocation or total utilization crosses 70%.
Use trigger-based optimization rather than periodic optimization. Monitor these signals:
- Token utilization above 80% — trigger compaction
- Attention degradation indicators (repetition, missed instructions) — trigger masking + compaction
- Quality score drops below baseline — audit context composition before optimizing
Practical Guidance
Optimization Decision Framework
Select the optimization technique based on what dominates the context:
| Context Composition | First Action | Second Action |
| Tool outputs dominate (>50%) | Observation masking | Compaction of remaining turns |
| Retrieved documents dominate | Summarization | Partitioning if docs are independent |
| Message history dominates | Compaction with selective preservation | Partitioning for new subtasks |
| Multiple components contribute | KV-cache optimization first, then layer masking + compaction | |
| Near-limit with active debugging | Mask resolved tool outputs only — preserve error details |
Performance Targets
Track these metrics to validate optimization effectiveness:
- Compaction: 50-70% token reduction, <5% quality degradation, <10% latency overhead from the compaction step itself
- Masking: 60-80% reduction in masked observations, <2% quality impact, near-zero latency overhead
- Cache optimization: 70%+ hit rate for stable workloads, 50%+ cost reduction, 40%+ latency reduction
- Partitioning: Net token savings after accounting for coordinator overhead; break-even typically requires 3+ subtasks
Iterate on strategies based on measured results. If an optimization technique does not measurably improve the target metric, remove it — optimization machinery itself consumes tokens and adds latency.
Examples
Example 1: Compaction Trigger
if context_tokens / context_limit > 0.8:
context = compact_context(context)Example 2: Observation Masking
if len(observation) > max_length:
ref_id = store_observation(observation)
return f"[Obs:{ref_id} elided. Key: {extract_key(observation)}]"Example 3: Cache-Friendly Ordering
# Stable content first
context = [system_prompt, tool_definitions] # Cacheable
context += [reused_templates] # Reusable
context += [unique_content] # UniqueExample 4: Budget-triggered optimization policy
budgets:
tool_outputs: 35%
message_history: 30%
retrieved_documents: 20%
reserved_buffer: 15%
triggers:
tool_outputs_over_budget: mask resolved observations
total_context_over_70_percent: compact message history
repeated_irrelevant_retrievals: tighten retrieval scopeGuidelines
- Measure before optimizing—know your current state
- Apply masking before compaction — remove low-value bulk first, then summarize what remains
- Design for cache stability with consistent prompts
- Partition before context becomes problematic
- Monitor optimization effectiveness over time
- Balance token savings against quality preservation
- Test optimization at production scale
- Implement graceful degradation for edge cases
Gotchas
- Whitespace breaks KV-cache: Even a single whitespace or newline change in the prompt prefix invalidates the entire KV-cache block downstream of that point. Pin system prompts as immutable strings — do not interpolate timestamps, version numbers, or session IDs into them. Diff prompt templates byte-for-byte between deployments.
- Timestamps in system prompts destroy cache hit rates: Including
Current date: {today}or similar dynamic content in the system prompt forces a full cache miss on every new day (or every request, if using time-of-day). Move dynamic metadata into a user message or a separate tool result appended after the stable prefix. - Compaction under pressure loses critical state: When the model performing compaction is itself under context pressure (>85% utilization), its summarization quality degrades — it omits task goals, drops user constraints, and flattens nuanced state. Trigger compaction at 70-80%, not 90%+. If compaction must happen late, use a separate model call with a clean context containing only the material to summarize.
- Masking error outputs breaks debugging loops: Over-aggressive masking hides error messages, stack traces, and failure details that the agent needs in subsequent turns to diagnose and fix issues. During active debugging (error in the last 3 turns), suspend masking for all error-related observations until the issue is resolved.
- Partitioning overhead can exceed savings: Each sub-agent requires its own system prompt, tool definitions, and coordination messages. For tasks with fewer than 3 independent subtasks, the coordination overhead often exceeds the context savings. Estimate total tokens (coordinator + all sub-agents) before committing to partitioning.
- Cache miss cost spikes after deployment changes: Reordering tools, rewording the system prompt, or changing few-shot examples between deployments invalidates the entire prefix cache, causing a temporary cost spike of 2-5x until the new cache warms up. Roll out prompt changes gradually and monitor cache hit rate during deployment windows.
- Compaction creates false confidence in stale summaries: Once context is compacted, the summary looks authoritative but may reflect outdated state. If the task has evolved since compaction (new user requirements, corrected assumptions), the summary silently carries forward stale information. After compaction, re-validate the summary against the current task goal before proceeding.
Integration
This skill owns token-efficiency tactics and budget policy. Adjacent skills own diagnosis, storage, and architecture:
context-fundamentals: mental models for why context quality and attention placement matter.context-degradation: diagnosis when output quality has already dropped.context-compression: lossy summarization and handoff strategy.filesystem-context: file-backed offloading for full outputs and logs.multi-agent-patterns: partitioning work across isolated agent contexts.latent-briefing: selective KV retention across orchestrator-worker boundaries in compatible runtimes.self-managed-context: the model, not the harness, decides when and what to edit in its live context.evaluation: measuring whether the optimization improved quality, cost, or latency.memory-systems: persistent retrieval layers that feed context just in time.
References
Internal reference:
- Optimization Techniques Reference - Read when: implementing a specific optimization technique and needing detailed code patterns, threshold tables, or integration examples beyond what the skill body provides
Related skills in this collection:
- context-fundamentals - Read when: unfamiliar with context window mechanics, token counting, or attention distribution basics
- context-degradation - Read when: diagnosing why agent performance has dropped and needing to identify which degradation pattern is occurring before selecting an optimization
- evaluation - Read when: setting up metrics and benchmarks to measure whether an optimization technique actually improved outcomes
External resources:
- Research on context window limitations - Read when: evaluating model-specific context behavior (e.g., lost-in-the-middle effects, attention decay curves)
- KV-cache optimization techniques - Read when: implementing prefix caching at the inference infrastructure level (vLLM, TGI, or cloud provider APIs)
- Production engineering guides - Read when: deploying context optimization in a production pipeline and needing operability patterns (monitoring, alerting, rollback)
Skill Metadata
Created: 2025-12-20 Last Updated: 2026-05-15 Author: Agent Skills for Context Engineering Contributors Version: 2.1.0
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

