Agent skill

Context Optimization

by agent-skills-hub in agent-skills-hub/agent-skills-hub

Apply compaction, masking, and caching strategies. An agent skill from agent-skills-hub/agent-skills-hub.

MITAuto-check passedAgent Workflows

Install Context Optimization

skills CLI
$ npx skills add agent-skills-hub/agent-skills-hub --skill context-optimization -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agent-skills-hub/agent-skills-hub context-optimization --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agent-skills-hub/agent-skills-hub.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/context-optimization .claude/skills/context-optimization && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
context-optimization
GitHub stars
111
Used in
1 other repo
Token cost
~2.1k tokens
SKILL.md length
970 words
Files
1
Skills in repo
12
Repo updated
First seen
Licence
MIT

At a glance

Apply compaction, masking, and caching strategies. An agent skill from agent-skills-hub/agent-skills-hub.

  • Works in 8 steps: Measure before optimizing—know your… → Apply compaction before masking when… → Design for cache stability with… → …
  • Tasks that involve Context engineering
  • SKILL.md covers When to Use This Skill, When to Activate, Core Concepts and Detailed Topics, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Context Optimization is an agent skill from agent-skills-hub/agent-skills-hub. Apply compaction, masking, and caching strategies

Its SKILL.md is about 2.1k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Agent Workflows, covering Context engineering and Caching. The repository describes itself as: Agent Skills Hub is a global library of AI agent skills that work across OpenClaw, Claude Code, Gemini, Cursor, Antigravity, and more. The licence is MIT.

When your agent uses it

  • Tasks that involve Context engineering
  • Tasks that involve Caching

Example prompts

  • “/context-optimization”

Requirements

  • Python 3

Workflow steps

8 steps, taken from the first numbered list in SKILL.md.

  1. Measure before optimizing—know your current state
  2. Apply compaction before masking when possible
  3. Design for cache stability with consistent prompts
  4. Partition before context becomes problematic
  5. Monitor optimization effectiveness over time
  6. Balance token savings against quality preservation
  7. Test optimization at production scale
  8. Implement graceful degradation for edge cases

What it can do on your machine

Read from SKILL.md and the folder at commit efc0b96. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Context Optimization loads about 2.1k tokens when it runs. Until then it costs about 18 tokens; SKILL.md has 970 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~18
When it runs · the whole SKILL.md, loaded when a task matches
~2.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from agent-skills-hub/agent-skills-hub at commit efc0b96, republished under its MIT licence (© agent-skills-hub). 970 words, ~2,129 tokens.

Download SKILL.mdSave it as .claude/skills/context-optimization/SKILL.md (or your agent's skills folder).
name
context-optimization
description
Apply compaction, masking, and caching strategies
source
https://github.com/muratcankoylan/Agent-Skills-for-Context-Engineering/tree/main/skills/context-optimization
risk
safe

When to Use This Skill

Apply compaction, masking, and caching strategies

Use this skill when working with apply compaction, masking, and caching strategies.

Context Optimization Techniques

Context optimization extends the effective capacity of limited context windows through strategic compression, masking, caching, and partitioning. The goal is not to magically increase context windows but to make better use of available capacity. Effective optimization can double or triple effective context capacity without requiring larger models or longer contexts.

When to Activate

Activate this skill when:

  • Context limits constrain task complexity
  • Optimizing for cost reduction (fewer tokens = lower costs)
  • Reducing latency for long conversations
  • Implementing long-running agent systems
  • Needing to handle larger documents or conversations
  • Building production systems at scale

Core Concepts

Context optimization extends effective capacity through four primary strategies: compaction (summarizing context near limits), observation masking (replacing verbose outputs with references), KV-cache optimization (reusing cached computations), and context partitioning (splitting work across isolated contexts).

The key insight is that context quality matters more than quantity. Optimization preserves signal while reducing noise. The art lies in selecting what to keep versus what to discard, and when to apply each technique.

Detailed Topics

Compaction Strategies

What is Compaction Compaction is the practice of summarizing context contents when approaching limits, then reinitializing a new context window with the summary. This distills the contents of a context window in a high-fidelity manner, enabling the agent to continue with minimal performance degradation.

Compaction typically serves as the first lever in context optimization. The art lies in selecting what to keep versus what to discard.

Compaction Implementation Compaction works by identifying sections that can be compressed, generating summaries that capture essential points, and replacing full content with summaries. Priority for compression goes to tool outputs (replace with summaries), old turns (summarize early conversation), retrieved docs (summarize if recent versions exist), and never compress system prompt.

Summary Generation Effective summaries preserve different elements depending on message type:

Tool outputs: Preserve key findings, metrics, and conclusions. Remove verbose raw output.

Conversational turns: Preserve key decisions, commitments, and context shifts. Remove filler and back-and-forth.

Retrieved documents: Preserve key facts and claims. Remove supporting evidence and elaboration.

Observation Masking

The Observation Problem Tool outputs can comprise 80%+ of token usage in agent trajectories. Much of this is verbose output that has already served its purpose. Once an agent has used a tool output to make a decision, keeping the full output provides diminishing value while consuming significant context.

Observation masking replaces verbose tool outputs with compact references. The information remains accessible if needed but does not consume context continuously.

Masking Strategy Selection Not all observations should be masked equally:

Never mask: Observations critical to current task, observations from the most recent turn, observations used in active reasoning.

Consider masking: Observations from 3+ turns ago, verbose outputs with key points extractable, observations whose purpose has been served.

Always mask: Repeated outputs, boilerplate headers/footers, outputs already summarized in conversation.

KV-Cache Optimization

Understanding KV-Cache The KV-cache stores Key and Value tensors computed during inference, growing linearly with sequence length. Caching the KV-cache across requests sharing identical prefixes avoids recomputation.

Prefix caching reuses KV blocks across requests with identical prefixes using hash-based block matching. This dramatically reduces cost and latency for requests with common prefixes like system prompts.

Cache Optimization Patterns Optimize for caching by reordering context elements to maximize cache hits. Place stable elements first (system prompt, tool definitions), then frequently reused elements, then unique elements last.

Design prompts to maximize cache stability: avoid dynamic content like timestamps, use consistent formatting, keep structure stable across sessions.

Show full SKILL.md (378 more words)Show less
Context Partitioning

Sub-Agent Partitioning The most aggressive form of context optimization is partitioning work across sub-agents with isolated contexts. Each sub-agent operates in a clean context focused on its subtask without carrying accumulated context from other subtasks.

This approach achieves separation of concerns—the detailed search context remains isolated within sub-agents while the coordinator focuses on synthesis and analysis.

Result Aggregation Aggregate results from partitioned subtasks by validating all partitions completed, merging compatible results, and summarizing if still too large.

Budget Management

Context Budget Allocation Design explicit context budgets. Allocate tokens to categories: system prompt, tool definitions, retrieved docs, message history, and reserved buffer. Monitor usage against budget and trigger optimization when approaching limits.

Trigger-Based Optimization Monitor signals for optimization triggers: token utilization above 80%, degradation indicators, and performance drops. Apply appropriate optimization techniques based on context composition.

Practical Guidance

Optimization Decision Framework

When to optimize:

  • Context utilization exceeds 70%
  • Response quality degrades as conversations extend
  • Costs increase due to long contexts
  • Latency increases with conversation length

What to apply:

  • Tool outputs dominate: observation masking
  • Retrieved documents dominate: summarization or partitioning
  • Message history dominates: compaction with summarization
  • Multiple components: combine strategies
Performance Considerations

Compaction should achieve 50-70% token reduction with less than 5% quality degradation. Masking should achieve 60-80% reduction in masked observations. Cache optimization should achieve 70%+ hit rate for stable workloads.

Monitor and iterate on optimization strategies based on measured effectiveness.

Examples

Example 1: Compaction Trigger

python
if context_tokens / context_limit > 0.8:
    context = compact_context(context)

Example 2: Observation Masking

python
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

python
# Stable content first
context = [system_prompt, tool_definitions]  # Cacheable
context += [reused_templates]  # Reusable
context += [unique_content]  # Unique

Guidelines

  1. Measure before optimizing—know your current state
  2. Apply compaction before masking when possible
  3. Design for cache stability with consistent prompts
  4. Partition before context becomes problematic
  5. Monitor optimization effectiveness over time
  6. Balance token savings against quality preservation
  7. Test optimization at production scale
  8. Implement graceful degradation for edge cases

Integration

This skill builds on context-fundamentals and context-degradation. It connects to:

  • multi-agent-patterns - Partitioning as isolation
  • evaluation - Measuring optimization effectiveness
  • memory-systems - Offloading context to memory

References

Internal reference:

Related skills in this collection:

  • context-fundamentals - Context basics
  • context-degradation - Understanding when to optimize
  • evaluation - Measuring optimization

External resources:

  • Research on context window limitations
  • KV-cache optimization techniques
  • Production engineering guides

Skill Metadata

Created: 2025-12-20 Last Updated: 2025-12-20 Author: Agent Skills for Context Engineering Contributors Version: 1.0.0

© agent-skills-hub, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/context-optimization of agent-skills-hub/agent-skills-hub.

Open the folder on GitHubat commit efc0b96

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in agent-skills-hub/agent-skills-hub, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Context Optimization next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Context Optimization compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Context Optimization this skillagent-skills-hub/agent-skills-hub1111 repos~2.1kAutomated safety check: PassMIT
xc-plugin State Managementconorluddy/xclaude-plugin183—~4kAutomated safety check: PassMIT
Context Optimizationguanyang/open-agent-hub9752 repos~4kAutomated safety check: PassMIT
Context Mode Output Sandboxmksglu/context-mode26k—~4.1kAutomated safety check: PassCustom licence
Memori Long-Term MemoryMemoriLabs/Memori17k—~2kAutomated safety check: NotesCustom licence
Picoclaw Skill Creatorsipeed/picoclaw30k—~4.4kAutomated safety check: PassMIT

Similar skills

  • xc-plugin State Management

    conorluddy/xclaude-plugin

    Teaches how xc-plugin saves tokens with progressive disclosure, cached responses and consistent configuration, so large device lists and build logs arrive as summaries first.

    183 GitHub stars~4k tokensUpdated 25 days ago
    Agent WorkflowsAuto-check passed
  • Context Optimization

    guanyang/open-agent-hub

    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…

    975 GitHub starsUsed in 2 repos~4k tokens
    Agent WorkflowsAuto-check passed
  • Context Mode Output Sandbox

    mksglu/context-mode

    Routes large command, file, API and browser output through context-mode tools so only the needed result enters the agent's context, instead of dumping it via Bash.

    26k GitHub stars~4.1k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Memori Long-Term Memory

    MemoriLabs/Memori

    Connects Claude Code to Memori Cloud for long-term memory, recalling stored context before substantive replies and saving new context afterward.

    17k GitHub stars~2k tokensUpdated 5 days ago
    Agent WorkflowsAuto-check: notes
  • Picoclaw Skill Creator

    sipeed/picoclaw

    Guidance for creating, updating and reviewing Picoclaw skills, from the SKILL.md structure to organizing bundled scripts, references and assets.

    30k GitHub stars~4.4k tokensUpdated 13 days ago
    Agent WorkflowsAuto-check passed
  • ccc Semantic Code Search

    cocoindex-io/cocoindex-code

    Semantic code search and index management with the ccc CLI: the agent initializes, indexes and queries the project by concept, filtering by language or path.

    2.7k GitHub stars~938 tokensUpdated yesterday
    Agent WorkflowsAuto-check passed

More from agent-skills-hub/agent-skills-hub

All 12 skills in this repo
  • Edgartools

    agent-skills-hub/agent-skills-hub

    Python library for accessing, analyzing, and extracting data from SEC EDGAR filings.

    111 GitHub starsUsed in 2 repos~1.4k tokens
    Auto-check passed
  • Build Sdf Liquid Glass

    agent-skills-hub/agent-skills-hub

    Build lightweight SDF/canvas displacement glass with Vaso. An agent skill from agent-skills-hub/agent-skills-hub.

    111 GitHub stars~674 tokensUpdated 5 days ago
    Auto-check passed
  • Mobile Design

    agent-skills-hub/agent-skills-hub

    Mobile-first design and engineering doctrine for iOS and Android apps.

    111 GitHub stars~2.3k tokensUpdated 5 days ago
    Auto-check: notes
  • Geomaster

    agent-skills-hub/agent-skills-hub

    Comprehensive geospatial science skill covering remote sensing, GIS, spatial analysis, machine learning for earth observation, and 30+ scientific domains.

    111 GitHub starsUsed in 1 repo~5.2k tokens
    Auto-check passed
  • AI Antislop

    agent-skills-hub/agent-skills-hub

    Anti-slop discipline for AI agent behavior across ALL domains — code, design/UI, security, writing, research, data, creative/media.

    111 GitHub stars~1.9k tokensUpdated 5 days ago
    Auto-check passed
  • Tiledbvcf

    agent-skills-hub/agent-skills-hub

    Efficient storage and retrieval of genomic variant data using TileDB.

    111 GitHub starsUsed in 4 repos~3.8k tokens
    Auto-check passed

Categories

Questions about Context Optimization

What does Context Optimization do?

Apply compaction, masking, and caching strategies. An agent skill from agent-skills-hub/agent-skills-hub. Context Optimization is an agent skill from agent-skills-hub/agent-skills-hub.

When should I use Context Optimization?

Context Optimization fits situations like: tasks that involve Context engineering; tasks that involve Caching.

How do I install Context Optimization in Claude Code?

Run `npx skills add agent-skills-hub/agent-skills-hub --skill context-optimization -a claude-code`. Or copy the skill folder (skills/context-optimization in agent-skills-hub/agent-skills-hub) into .claude/skills/context-optimization in your project. Claude Code loads it when a task matches its description.

How do I install Context Optimization in Codex?

Run `npx skills add agent-skills-hub/agent-skills-hub --skill context-optimization -a codex`. Or copy the skill folder (skills/context-optimization in agent-skills-hub/agent-skills-hub) into .agents/skills/context-optimization in your project. Codex loads it when a task matches its description.

Can I use Context Optimization in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agent-skills-hub/agent-skills-hub --skill context-optimization -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/context-optimization, .gemini/skills/context-optimization, .github/skills/context-optimization and .opencode/skills/context-optimization in your project.

What does Context Optimization need to run?

SKILL.md names no scripts, command-line tools or credentials: Context Optimization is instructions for the agent only. Our summary lists: Python 3.

Does Context Optimization access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Context Optimization safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Context Optimization use?

Context Optimization is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Context Optimization use?

About 2.1k tokens (SKILL.md is roughly 8.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Context Optimization?

Skills that share tags, products or a category with Context Optimization: xc-plugin State Management (conorluddy/xclaude-plugin, 183 stars), Context Optimization (guanyang/open-agent-hub, 975 stars), Context Mode Output Sandbox (mksglu/context-mode, 26k stars) and Memori Long-Term Memory (MemoriLabs/Memori, 17k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Context Optimization?

agent-skills-hub (a GitHub organization) maintains it in agent-skills-hub/agent-skills-hub, which has 111 GitHub stars. The repository holds 12 skills in this directory. The repository was last updated on October 2, 2026.

Source: agent-skills-hub/agent-skills-hub on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.