
Context Optimization
- 12 installs
- 1 repo stars
- Updated January 27, 2026
- bilalmk/todo_correct
context-optimization is a Claude Code skill that applies compaction, masking, caching, and partitioning to extend effective context capacity.
About
This skill applies techniques to extend the effective capacity of a limited context window. It covers compaction (summarizing near limits), observation masking (replacing verbose tool outputs with references), KV-cache optimization, and context partitioning across sub-agents. A developer uses it when context limits constrain performance or when reducing token cost and latency for long-running agents. It matters because these techniques can multiply usable capacity without a larger model.
- Covers four strategies: compaction, observation masking, KV-cache optimization, and context partitioning
- Explains masking tool outputs that can consume 80%+ of trajectory tokens
- Provides a trigger-based optimization framework (optimize when utilization exceeds 70%)
Context Optimization by the numbers
- 12 all-time installs (skills.sh)
- Ranked #11,592 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Jul 28, 2026 (Skillselion catalog sync)
context-optimization capabilities & compatibility
- Capabilities
- token optimization
- Use cases
- token optimization · orchestration
- Runs
- Runs locally
- Pricing
- Free
What context-optimization says it does
Apply optimization techniques to extend effective context capacity.
Context optimization extends effective capacity through four primary strategies: compaction (summarizing context near limits), observation masking (replacing verbose outputs with references), KV-cache
Tool outputs can comprise 80%+ of token usage in agent trajectories.
npx skills add https://github.com/bilalmk/todo_correct --skill context-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 12 |
|---|---|
| repo stars | ★ 1 |
| Last updated | January 27, 2026 |
| Repository | bilalmk/todo_correct ↗ |
What it does
Extend effective context capacity and cut token cost for a long-running agent using compaction, masking, and partitioning.
Who is it for?
Reducing token cost or handling larger conversations in a long-running agent.
When should I use this skill?
Context limits constrain agent performance, or you are optimizing for cost or latency.
What you get
Extends usable context capacity by preserving signal while discarding noise.
By the numbers
- Covers 4 primary optimization strategies
- Notes tool outputs can comprise 80%+ of token usage
Files
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.
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
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] # UniqueGuidelines
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:
- Optimization Techniques Reference - Detailed technical 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
Context Optimization Reference
This document provides detailed technical reference for context optimization techniques and strategies.
Compaction Strategies
Summary-Based Compaction
Summary-based compaction replaces verbose content with concise summaries while preserving key information. The approach works by identifying sections that can be compressed, generating summaries that capture essential points, and replacing full content with summaries.
The effectiveness of compaction depends on what information is preserved. Critical decisions, user preferences, and current task state should never be compacted. Intermediate results and supporting evidence can be summarized more aggressively. Boilerplate, repeated information, and exploratory reasoning can often be removed entirely.
Token Budget Allocation
Effective context budgeting requires understanding how different context components consume tokens and allocating budget strategically:
| Component | Typical Range | Notes |
|---|---|---|
| System prompt | 500-2000 tokens | Stable across session |
| Tool definitions | 100-500 per tool | Grows with tool count |
| Retrieved documents | Variable | Often largest consumer |
| Message history | Variable | Grows with conversation |
| Tool outputs | Variable | Can dominate context |
Compaction Thresholds
Trigger compaction at appropriate thresholds to maintain performance:
- Warning threshold at 70% of effective context limit
- Compaction trigger at 80% of effective context limit
- Aggressive compaction at 90% of effective context limit
The exact thresholds depend on model behavior and task characteristics. Some models show graceful degradation while others exhibit sharp performance cliffs.
Observation Masking Patterns
Selective Masking
Not all observations should be masked equally. Consider masking observations that have served their purpose and are no longer needed for active reasoning. Keep observations that are central to the current task. Keep observations from the most recent turn. Keep observations that may be referenced again.
Masking Implementation
def selective_mask(observations: List[Dict], current_task: Dict) -> List[Dict]:
"""
Selectively mask observations based on relevance.
Returns observations with mask field indicating masked content.
"""
masked = []
for obs in observations:
relevance = calculate_relevance(obs, current_task)
if relevance < 0.3 and obs["age"] > 3:
# Low relevance and old - mask
masked.append({
**obs,
"masked": True,
"reference": store_for_reference(obs["content"]),
"summary": summarize_content(obs["content"])
})
else:
masked.append({
**obs,
"masked": False
})
return maskedKV-Cache Optimization
Prefix Stability
KV-cache hit rates depend on prefix stability. Stable prefixes enable cache reuse across requests. Dynamic prefixes invalidate cache and force recomputation.
Elements that should remain stable include system prompts, tool definitions, and frequently used templates. Elements that may vary include timestamps, session identifiers, and query-specific content.
Cache-Friendly Design
Design prompts to maximize cache hit rates:
1. Place stable content at the beginning 2. Use consistent formatting across requests 3. Avoid dynamic content in prompts when possible 4. Use placeholders for dynamic content
# Cache-unfriendly: Dynamic timestamp in prompt
system_prompt = f"""
Current time: {datetime.now().isoformat()}
You are a helpful assistant.
"""
# Cache-friendly: Stable prompt with dynamic time as variable
system_prompt = """
You are a helpful assistant.
Current time is provided separately when relevant.
"""Context Partitioning Strategies
Sub-Agent Isolation
Partition work across sub-agents to prevent any single context from growing too large. Each sub-agent operates with a clean context focused on its subtask.
Partition Planning
def plan_partitioning(task: Dict, context_limit: int) -> Dict:
"""
Plan how to partition a task based on context limits.
Returns partitioning strategy and subtask definitions.
"""
estimated_context = estimate_task_context(task)
if estimated_context <= context_limit:
return {
"strategy": "single_agent",
"subtasks": [task]
}
# Plan multi-agent approach
subtasks = decompose_task(task)
return {
"strategy": "multi_agent",
"subtasks": subtasks,
"coordination": "hierarchical"
}Optimization Decision Framework
When to Optimize
Consider context optimization when context utilization exceeds 70%, when response quality degrades as conversations extend, when costs increase due to long contexts, or when latency increases with conversation length.
What Optimization to Apply
Choose optimization strategies based on context composition:
If tool outputs dominate context, apply observation masking. If retrieved documents dominate context, apply summarization or partitioning. If message history dominates context, apply compaction with summarization. If multiple components contribute, combine strategies.
Evaluation of Optimization
After applying optimization, evaluate effectiveness:
- Measure token reduction achieved
- Measure quality preservation (output quality should not degrade)
- Measure latency improvement
- Measure cost reduction
Iterate on optimization strategies based on evaluation results.
Common Pitfalls
Over-Aggressive Compaction
Compacting too aggressively can remove critical information. Always preserve task goals, user preferences, and recent conversation context. Test compaction at increasing aggressiveness levels to find the optimal balance.
Masking Critical Observations
Masking observations that are still needed can cause errors. Track observation usage and only mask content that is no longer referenced. Consider keeping references to masked content that could be retrieved if needed.
Ignoring Attention Distribution
The lost-in-middle phenomenon means that information placement matters. Place critical information at attention-favored positions (beginning and end of context). Use explicit markers to highlight important content.
Premature Optimization
Not all contexts require optimization. Adding optimization machinery has overhead. Optimize only when context limits actually constrain agent performance.
Monitoring and Alerting
Key Metrics
Track these metrics to understand optimization needs:
- Context token count over time
- Cache hit rates for repeated patterns
- Response quality metrics by context size
- Cost per conversation by context length
- Latency by context size
Alert Thresholds
Set alerts for:
- Context utilization above 80%
- Cache hit rate below 50%
- Quality score drop of more than 10%
- Cost increase above baseline
Integration Patterns
Integration with Agent Framework
Integrate optimization into agent workflow:
class OptimizingAgent:
def __init__(self, context_limit: int = 80000):
self.context_limit = context_limit
self.optimizer = ContextOptimizer()
def process(self, user_input: str, context: Dict) -> Dict:
# Check if optimization needed
if self.optimizer.should_compact(context):
context = self.optimizer.compact(context)
# Process with optimized context
response = self._call_model(user_input, context)
# Track metrics
self.optimizer.record_metrics(context, response)
return responseIntegration with Memory Systems
Connect optimization with memory systems:
class MemoryAwareOptimizer:
def __init__(self, memory_system, context_limit: int):
self.memory = memory_system
self.limit = context_limit
def optimize_context(self, current_context: Dict, task: str) -> Dict:
# Check if information is in memory
relevant_memories = self.memory.retrieve(task)
# Move information to memory if not needed in context
for mem in relevant_memories:
if mem["importance"] < threshold:
current_context = remove_from_context(current_context, mem)
# Keep reference that memory can be retrieved
return current_contextPerformance Benchmarks
Compaction Performance
Compaction should reduce token count while preserving quality. Target:
- 50-70% token reduction for aggressive compaction
- Less than 5% quality degradation from compaction
- Less than 10% latency increase from compaction overhead
Masking Performance
Observation masking should reduce token count significantly:
- 60-80% reduction in masked observations
- Less than 2% quality impact from masking
- Near-zero latency overhead
Cache Performance
KV-cache optimization should improve cost and latency:
- 70%+ cache hit rate for stable workloads
- 50%+ cost reduction from cache hits
- 40%+ latency reduction from cache hits
"""
Context Optimization Utilities
This module provides utilities for context compaction, observation masking, and budget management.
PRODUCTION NOTES:
- Token estimation uses simplified heuristics (~4 chars/token for English).
Production systems should use model-specific tokenizers:
- OpenAI: tiktoken library
- Anthropic: anthropic tokenizer
- Local models: HuggingFace tokenizers
- Summarization functions use simple heuristics for demonstration.
Production systems should use:
- LLM-based summarization for high-quality compression
- Domain-specific summarization models
- Schema-based summarization for structured outputs
- Cache metrics are illustrative. Production systems should integrate
with actual inference infrastructure metrics.
"""
from typing import List, Dict
import hashlib
import time
def estimate_token_count(text: str) -> int:
"""
Estimate token count for text.
Uses approximation: ~4 characters per token for English.
WARNING: This is a rough estimate. Actual tokenization varies by:
- Model (GPT-5.2, Claude 4.5, Gemini 3 have different tokenizers)
- Content type (code typically has higher token density)
- Language (non-English may have 2-3x higher token/char ratio)
Production usage:
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4") # Use appropriate model
token_count = len(enc.encode(text))
"""
return len(text) // 4
def estimate_message_tokens(messages: list) -> int:
"""Estimate token count for message list."""
total = 0
for msg in messages:
# Count content
content = msg.get("content", "")
total += estimate_token_count(content)
# Add overhead for role/formatting
total += 10
return total
# Compaction Functions
def categorize_messages(messages: list) -> dict:
"""
Categorize messages for selective compaction.
Returns dict mapping category to messages.
"""
categories = {
"system_prompt": [],
"tool_definition": [],
"tool_output": [],
"conversation": [],
"retrieved_document": [],
"other": []
}
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
if role == "system":
categories["system_prompt"].append({**msg, "category": "system_prompt"})
elif "tool_use" in msg.get("type", ""):
categories["tool_output"].append({**msg, "category": "tool_output"})
elif role == "user":
categories["conversation"].append({**msg, "category": "conversation"})
elif "retrieved" in msg.get("tags", []):
categories["retrieved_document"].append({**msg, "category": "retrieved_document"})
else:
categories["other"].append({**msg, "category": "other"})
return categories
def summarize_content(content: str, category: str, max_length: int = 500) -> str:
"""
Summarize content for compaction.
Different summarization for different categories.
"""
if category == "tool_output":
return summarize_tool_output(content, max_length)
elif category == "conversation":
return summarize_conversation(content, max_length)
elif category == "retrieved_document":
return summarize_document(content, max_length)
else:
return summarize_general(content, max_length)
def summarize_tool_output(content: str, max_length: int = 500) -> str:
"""Summarize tool output."""
# Extract key metrics and findings
import re
# Look for metrics (numbers with context)
metrics = re.findall(r'(\w+):\s*([\d.,]+)', content)
# Look for key findings (lines with important keywords)
keywords = ["result", "found", "total", "success", "error", "value"]
findings = []
for line in content.split('\n'):
if any(kw in line.lower() for kw in keywords):
findings.append(line.strip())
summary_parts = []
if metrics:
summary_parts.append(f"Metrics: {', '.join([f'{k}={v}' for k, v in metrics])}")
if findings:
summary_parts.append("Key findings: " + "; ".join(findings[:3]))
result = " | ".join(summary_parts) if summary_parts else "[Tool output summarized]"
return result[:max_length]
def summarize_conversation(content: str, max_length: int = 500) -> str:
"""Summarize conversational content."""
# Identify key decisions and questions
import re
decisions = re.findall(r'(?i)(?:decided|decision|chose|chosen)[:\s]+([^.]+)', content)
questions = re.findall(r'(?:\?|question)[:\s]+([^.]+)', content)
summary_parts = []
if decisions:
summary_parts.append(f"Decisions: {len(decisions)} made")
if questions:
summary_parts.append(f"Questions: {len(questions)} raised")
result = " | ".join(summary_parts) if summary_parts else "[Conversation summarized]"
return result[:max_length]
def summarize_document(content: str, max_length: int = 500) -> str:
"""Summarize document content."""
# Extract first paragraph as summary
paragraphs = content.split('\n\n')
if paragraphs:
first_para = paragraphs[0].strip()
# Truncate to first few sentences
sentences = first_para.split('. ')
if len(sentences) > 2:
first_para = '. '.join(sentences[:2]) + '.'
return first_para[:max_length]
return "[Document summarized]"
def summarize_general(content: str, max_length: int = 500) -> str:
"""General purpose summarization."""
return content[:max_length] + "..." if len(content) > max_length else content
# Observation Masking
class ObservationStore:
def __init__(self, max_size=1000):
self.observations = {}
self.order = []
self.max_size = max_size
def store(self, content: str, metadata: dict = None) -> str:
"""Store observation and return reference ID."""
ref_id = self._generate_ref_id(content)
self.observations[ref_id] = {
"content": content,
"metadata": metadata or {},
"stored_at": time.time(),
"last_accessed": time.time()
}
self.order.append(ref_id)
# Evict oldest if over limit
if len(self.order) > self.max_size:
oldest = self.order.pop(0)
del self.observations[oldest]
return ref_id
def retrieve(self, ref_id: str) -> str:
"""Retrieve observation by reference ID."""
if ref_id in self.observations:
self.observations[ref_id]["last_accessed"] = time.time()
return self.observations[ref_id]["content"]
return None
def mask(self, content: str, max_length: int = 200) -> tuple:
"""
Mask observation if longer than max_length.
Returns (masked_content, stored_ref_id_or_None).
"""
if len(content) <= max_length:
return content, None
ref_id = self.store(content)
# Extract key point for reference
key_point = self._extract_key_point(content)
masked = f"[Obs:{ref_id} elided. Key: {key_point}. Full content retrievable.]"
return masked, ref_id
def _generate_ref_id(self, content: str) -> str:
"""Generate unique reference ID."""
hash_input = f"{content[:100]}{time.time()}"
return hashlib.md5(hash_input.encode()).hexdigest()[:8]
def _extract_key_point(self, content: str) -> str:
"""Extract key point from observation."""
# First substantial line or sentence
lines = [l for l in content.split('\n') if len(l) > 20]
if lines:
return lines[0][:50] + "..."
sentences = content.split('. ')
if sentences:
return sentences[0][:50] + "..."
return content[:50] + "..."
# Context Budget Management
class ContextBudget:
def __init__(self, total_limit: int):
self.total_limit = total_limit
self.allocated = {
"system_prompt": 0,
"tool_definitions": 0,
"retrieved_docs": 0,
"message_history": 0,
"tool_outputs": 0,
"other": 0
}
self.reserved = 5000 # Reserved buffer
self.reservation_limit = total_limit - self.reserved
def allocate(self, category: str, amount: int) -> bool:
"""Allocate budget to category. Returns success status."""
if category not in self.allocated:
category = "other"
current = sum(self.allocated.values())
proposed = current + amount
if proposed > self.reservation_limit:
return False
self.allocated[category] += amount
return True
def remaining(self) -> int:
"""Get remaining unallocated budget."""
current = sum(self.allocated.values())
return self.reservation_limit - current
def get_usage(self) -> dict:
"""Get current usage breakdown."""
total = sum(self.allocated.values())
return {
"total_used": total,
"total_limit": self.total_limit,
"remaining": self.remaining(),
"by_category": dict(self.allocated),
"utilization_ratio": total / self.total_limit
}
def should_optimize(self, current_usage: int, metrics: dict = None) -> tuple:
"""
Determine if optimization should trigger.
Returns (should_optimize, reasons).
"""
reasons = []
# Check utilization
utilization = current_usage / self.total_limit
if utilization > 0.8:
reasons.append(("high_utilization", utilization))
# Check degradation metrics if provided
if metrics:
if metrics.get("attention_degradation", 0) > 0.3:
reasons.append(("attention_degradation", True))
if metrics.get("quality_score", 1.0) < 0.8:
reasons.append(("quality_degradation", True))
should_optimize = len(reasons) > 0
return should_optimize, reasons
# Cache Optimization
def design_stable_prompt(template: str, dynamic_values: dict) -> str:
"""
Design prompt to maximize KV-cache stability.
Replaces dynamic values with stable placeholders.
"""
result = template
# Replace timestamps
import re
date_pattern = r'\d{4}-\d{2}-\d{2}'
result = re.sub(date_pattern, '[DATE_STABLE]', result)
# Replace session IDs
session_pattern = r'Session \d+'
result = re.sub(session_pattern, 'Session [STABLE]', result)
# Replace counters
counter_pattern = r'\d+/\d+'
result = re.sub(counter_pattern, '[COUNTER_STABLE]', result)
return result
def calculate_cache_metrics(requests: list, cache: dict) -> dict:
"""
Calculate KV-cache hit metrics for request sequence.
"""
hits = 0
misses = 0
for req in requests:
prefix = req.get("prefix_hash", "")
token_count = req.get("token_count", 0)
if prefix in cache:
hits += token_count * cache[prefix].get("hit_ratio", 0)
else:
misses += token_count
total = hits + misses
return {
"hit_rate": hits / total if total > 0 else 0,
"cache_hits": hits,
"cache_misses": misses,
"recommendations": generate_cache_recommendations(hits, misses)
}
def generate_cache_recommendations(hits: int, misses: int) -> list:
"""Generate recommendations for cache optimization."""
recommendations = []
hit_rate = hits / (hits + misses) if (hits + misses) > 0 else 0
if hit_rate < 0.5:
recommendations.append("Consider stabilizing system prompts")
recommendations.append("Reduce variation in request prefixes")
if hit_rate < 0.8:
recommendations.append("Group similar requests together")
recommendations.append("Use consistent formatting across requests")
return recommendations
#!/usr/bin/env python3
"""Verify skill structure and content."""
import sys
from pathlib import Path
def main():
skill_dir = Path(__file__).parent.parent
skill_md = skill_dir / "SKILL.md"
if not skill_md.exists():
print("✗ SKILL.md not found")
sys.exit(1)
content = skill_md.read_text()
# Check frontmatter
if not content.startswith("---"):
print("✗ Missing YAML frontmatter")
sys.exit(1)
# Check required sections
required = ["When to Activate", "Core Concepts", "Guidelines"]
missing = [s for s in required if s not in content]
if missing:
print(f"✗ Missing sections: {', '.join(missing)}")
sys.exit(1)
print(f"✓ {skill_dir.name} skill validated")
sys.exit(0)
if __name__ == "__main__":
main()