Best for
- Use when retrieved or assembled material is noisy or exceeds the useful context budget; use context-ranking for scoring chunks and context-compression for shrinking selected content.
seb1n/awesome-ai-agent-skills/context-engineering/context-optimization/SKILL.md
Optimize a complete candidate context package by deduplicating, filtering, ordering, and allocating its token budget. Use when retrieved or assembled material is noisy or exceeds the useful context budget; use context-ranking for scoring chunks and context-compression for shrinking selected content.
Decision brief
Context optimization is the process of refining the raw context assembled for an AI model so that every token contributes meaningfully to the task. In a typical RAG or agent pipeline, the retrieved context often contains redundant passages, marginally relevant chunks, and poorly…
Compatibility matrix
| Platform | Status | Evidence | What to check |
|---|---|---|---|
| Codex | Not declared | No explicit evidence | Portability before use |
| Claude Code | Not declared | No explicit evidence | Portability before use |
| Cursor | Not declared | No explicit evidence | Portability before use |
| Gemini CLI | Not declared | No explicit evidence | Portability before use |
Installation
The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.
npx skills add https://github.com/seb1n/awesome-ai-agent-skills --skill "context-engineering/context-optimization"Inspect the Agent Skill "context-optimization" from https://github.com/seb1n/awesome-ai-agent-skills/blob/75865a5d037a4cdaa7f409a4ec14ab9b0292920b/context-engineering/context-optimization/SKILL.md at commit 75865a5d037a4cdaa7f409a4ec14ab9b0292920b. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.
Workflow
1. Audit the Raw Context: Inventory every piece of context that has been gathered -- retrieved documents, conversation history, tool outputs, and metadata. Measure the total token count and compare it against the available context budget. Identify the compression ratio needed if…
Provide the raw context (a list of text chunks with optional metadata and scores), the user query, and the target token budget. The skill returns an optimized context block -- deduplicated, filtered, scored, and reordered -- ready for prompt assembly. Optionally provide a covera…
Deduplication: Identifies and removes redundant passages using semantic similarity thresholds or n-gram overlap detection. Critical in RAG pipelines where overlapping chunks often repeat the same sentences. Keeps the mo…
Task: "Refactor the authentication module to use async/await instead of callbacks."
Task: "Refactor the authentication module to use async/await instead of callbacks."
Permission review
No configured static risk pattern was detected
This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.
Evidence record
| Signal | Value | Evidence type | Meaning |
|---|---|---|---|
| Quality score | 91/100 | Computed | Documentation, specificity, maintenance, and trust rules |
| Repository stars | 161 | Source | Repository attention, not individual Skill quality |
| Compatibility | 0 platforms | Source | Declared in the catalog source record |
| Usage guide | automated source guide | Editorial | Generated or reviewed according to the visible evidence level |
Pinned source
Context optimization is the process of refining the raw context assembled for an AI model so that every token contributes meaningfully to the task. In a typical RAG or agent pipeline, the retrieved context often contains redundant passages, marginally relevant chunks, and poorly ordered information. Optimization transforms this raw material into a lean, high-signal context block that improves answer quality, reduces inference cost, and makes the most of the model's attention budget.
Audit the Raw Context: Inventory every piece of context that has been gathered -- retrieved documents, conversation history, tool outputs, and metadata. Measure the total token count and compare it against the available context budget. Identify the compression ratio needed if the raw context exceeds the budget.
Deduplicate Overlapping Content: Scan the context for near-duplicate passages that convey the same information. This is common in RAG pipelines where chunking with overlap produces multiple chunks covering the same paragraph, or when multiple source documents repeat the same facts. Use semantic similarity (cosine distance > 0.92) or exact n-gram overlap detection to identify duplicates, then keep only the most complete version of each piece of information.
Score Relevance and Information Density: Assign each context chunk two scores: a relevance score (how closely it relates to the current query) and an information density score (how many useful facts it conveys per token). Relevance can be measured via the retrieval score or a lightweight cross-encoder pass. Density can be estimated by counting named entities, code identifiers, numerical data, and key terms relative to chunk length. Multiply the two scores to produce a composite utility score.
Filter Low-Value Content: Remove chunks whose composite utility score falls below a threshold. A good starting point is to keep the top 60-70% of chunks by utility score. Also remove boilerplate text (copyright notices, navigation menus, repeated headers) that contributes zero information. Be conservative -- it is better to include a marginally relevant chunk than to lose a critical fact.
Reorder by Priority: Arrange the remaining chunks to maximize the model's attention. Place the highest-utility chunks first (models attend most to the beginning of the context) and the second-highest near the end (models also attend to recency). Avoid burying critical information in the middle of a long context block -- this is the "lost in the middle" zone where model attention is weakest.
Validate Coverage: After filtering and reordering, verify that the optimized context still covers all aspects of the query. If the query has multiple sub-questions, ensure at least one chunk addresses each. If coverage gaps appear, selectively re-add previously filtered chunks that fill the gap, even if their utility score was below the threshold.
Provide the raw context (a list of text chunks with optional metadata and scores), the user query, and the target token budget. The skill returns an optimized context block -- deduplicated, filtered, scored, and reordered -- ready for prompt assembly. Optionally provide a coverage checklist (key topics the context must address) to prevent important information from being filtered out.
Task: "Refactor the authentication module to use async/await instead of callbacks."
Raw Context (7 chunks, ~4,200 tokens):
| # | Source | Relevance | Density | Content Summary |
|---|---|---|---|---|
| 1 | src/auth/login.js:1-45 | 0.93 | High | Login function using callback-based db.findUser() |
| 2 | src/auth/login.js:20-55 | 0.90 | High | Overlapping chunk -- duplicates lines 20-45 of chunk 1, adds token refresh logic |
| 3 | src/auth/middleware.js:1-30 | 0.88 | High | Auth middleware with callback-based token verification |
| 4 | README.md:100-130 | 0.45 | Low | Project setup instructions -- no code, no auth details |
| 5 | src/auth/register.js:1-40 | 0.82 | High | Registration function using callbacks |
| 6 | package.json:1-25 | 0.35 | Low | Dependency list -- no auth-related logic |
| 7 | src/auth/login.js:40-70 | 0.91 | High | Token generation and session creation with callbacks |
Optimization Steps:
login.js.package.json, relevance 0.35) -- below the 0.50 threshold.Optimized Context (~2,800 tokens, 33% reduction):
src/auth/login.js:1-55 (merged) -- Login function with callback-based DB lookup and token refreshsrc/auth/login.js:40-70 -- Token generation and session creationsrc/auth/middleware.js:1-30 -- Auth middleware with callback token verificationsrc/auth/register.js:1-40 -- Registration function using callbacksQuery: "What is the company's return policy for electronics?"
Raw Retrieved Chunks (6 chunks, ~3,000 tokens):
returns-policy.md (score 0.95) -- "Electronics purchased from our store may be returned within 30 days of purchase. Items must be in original packaging with all accessories. A 15% restocking fee applies to opened items."faq.md (score 0.88) -- "Q: Can I return electronics? A: Yes, within 30 days. Items must be in original packaging. A 15% restocking fee applies to opened items. See our returns policy for full details."holiday-policy.md (score 0.72) -- "During the holiday season (Nov 15 - Jan 15), the return window for all products, including electronics, is extended to 60 days. All other conditions apply."shipping-info.md (score 0.40) -- "We ship electronics via insured ground shipping. Delivery takes 3-7 business days."returns-policy.md (score 0.85) -- "Refunds are processed to the original payment method within 5-10 business days. Defective items are exempt from the restocking fee and may be returned within 90 days."store-locator.md (score 0.30) -- "Visit any of our 200 retail locations nationwide."Optimization Steps:
Optimized Context (~900 tokens, 70% reduction):
Frequently asked questions
Context optimization is the process of refining the raw context assembled for an AI model so that every token contributes meaningfully to the task. In a typical RAG or agent pipeline, the retrieved context often contains redundant passages, marginally relevant chunks, and poorly…
The source record exposes this install command: npx skills add https://github.com/seb1n/awesome-ai-agent-skills --skill "context-engineering/context-optimization". Inspect the command and pinned source before running it.
Alternatives
garrytan/gbrain
End-to-end discipline for turning any large data source (audio libraries, email takeouts, document corpora, chat exports, API dumps) into brain pages at scale. The lifecycle spine: SCHEMA → ACCESS → TRIAL → EVALUATE → IMPROVE → CODIFY → TEST → SKILLIFY → BULK → MONITOR. State is tracked in a durable JSON manifest (see MANIFEST-PATTERN.md) so any crash, session boundary, or subagent fan-out resumes from ground truth instead of memory.
alirezarezvani/claude-skills
App Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklist
dotnet/skills
Migrates .NET test projects from VSTest to Microsoft.Testing.Platform (MTP). Use when user asks to "migrate to MTP", "switch from VSTest", "enable Microsoft.Testing.Platform", "use MTP runner", set OutputType=Exe only for test projects in Directory.Build.props, or mentions EnableMSTestRunner, EnableNUnitRunner, or UseMicrosoftTestingPlatformRunner. USE FOR: MTP behavioral differences vs VSTest (exit code 8, zero tests discovered, --ignore-exit-code, TESTINGPLATFORM_EXITCODE_IGNORE); centralizing
oaustegard/claude-skills
Generate hierarchical _FEATURES.md files that describe what a codebase DOES from a user/consumer perspective, anchored to source symbols via tree-sitting. Supports large complex codebases through feature-driven decomposition into sub-feature files. Uses a multi-pass synthesis: orientation → detail → overview rewrite. Use when someone says "what does this do", "document features", "feature inventory", "_FEATURES.md", or needs to understand a codebase's purpose before modifying it. Complements tre