AgentSkillsCN

context-optimization

触发条件:上下文、优化 运用 MECW 原则(将上下文使用率控制在总窗口的 50% 以内)来减少上下文使用。 触发条件:上下文压力、Token 使用、MECW、上下文窗口、优化、分解、工作流拆分、上下文管理、Token 优化 适用场景:上下文使用率接近窗口的 50%,任务需要分解,计划复杂的多步骤操作,上下文压力较大 禁忌场景:上下文使用率较低、仅需简单单步任务时使用。 禁忌场景:已通过 mcp-code-execution 实现工具链自动化时使用。 在开始复杂任务之前,务必先使用此技能。主动检查上下文使用水平。

SKILL.md
--- frontmatter
name: context-optimization
description: |
  Triggers: context, optimization
  Reduce context usage with MECW principles (keep under 50% of total window).

  Triggers: context pressure, token usage, MECW, context window, optimization,
  decomposition, workflow splitting, context management, token optimization

  Use when: context usage approaches 50% of window, tasks need decomposition,
  complex multi-step operations planned, context pressure is high

  DO NOT use when: simple single-step tasks with low context usage.
  DO NOT use when: already using mcp-code-execution for tool chains.

  Use this skill BEFORE starting complex tasks. Check context levels proactively.
category: conservation
token_budget: 150
progressive_loading: true

# Claude Code 2.1.0+ lifecycle hooks
hooks:
  PreToolUse:
    - matcher: Read
      command: |
        echo "[skill:context-optimization] 📊 Context analysis started: $(date)" >> ${CLAUDE_CODE_TMPDIR:-/tmp}/skill-audit.log
      once: true
  PostToolUse:
    - matcher: Bash
      command: |
        # Track context analysis tools
        if echo "$CLAUDE_TOOL_INPUT" | grep -qE "(wc|tokei|cloc|context)"; then
          echo "[skill:context-optimization] Context measurement executed: $(date)" >> ${CLAUDE_CODE_TMPDIR:-/tmp}/skill-audit.log
        fi
  Stop:
    - command: |-
        echo "[skill:context-optimization] === Optimization completed at $(date) ===" >> ${CLAUDE_CODE_TMPDIR:-/tmp}/skill-audit.log
        # Could export: context pressure events over time

Table of Contents

Context Optimization Hub

Quick Start

Basic Usage

bash
# Analyze current context usage
python -m conserve.context_analyzer

When to Use

  • Threshold Alert: When context usage approaches 50% of the window.
  • Complex Tasks: For operations requiring multi-file analysis or long tool chains.

Core Hub Responsibilities

  1. Assess context pressure and MECW compliance.
  2. Route to appropriate specialized modules.
  3. Coordinate subagent-based workflows.
  4. Manage token budget allocation across modules.
  5. Synthesize results from modular execution.

Module Selection Strategy

python
def select_optimal_modules(context_situation, task_complexity):
    if context_situation == "CRITICAL":
        return ['mecw-assessment', 'subagent-coordination']
    elif task_complexity == 'high':
        return ['mecw-principles', 'subagent-coordination']
    else:
        return ['mecw-assessment']

Context Classification

UtilizationStatusAction
< 30%LOWContinue normally
30-50%MODERATEMonitor, apply principles
> 50%CRITICALImmediate optimization required

Large Output Handling (Claude Code 2.1.2+)

Behavior Change: Large bash command and tool outputs are saved to disk instead of being truncated; file references are provided for access.

Impact on Context Optimization

ScenarioBefore 2.1.2After 2.1.2
Large test outputTruncated, partial dataFull output via file reference
Verbose build logsLost after 30K charsComplete, accessible on-demand
Context pressureLess from truncationSame - only loaded when read

Best Practices

  • Avoid pre-emptive reads: Large outputs are referenced, not automatically loaded into context.
  • Read selectively: Use head, tail, or grep on file references.
  • Leverage full data: Quality gates can access complete test results via files.
  • Monitor growth: File references are small, but reading the full files adds to context.

Integration Points

  • Token Conservation: Receives usage strategies, returns MECW-compliant optimizations.
  • CPU/GPU Performance: Aligns context optimization with resource constraints.
  • MCP Code Execution: Delegates complex patterns to specialized MCP modules.

Resources

  • MECW Theory: See modules/mecw-principles.md for core concepts and the 50% rule.
  • Context Analysis: See modules/mecw-assessment.md for risk identification.
  • Workflow Delegation: See modules/subagent-coordination.md for decomposition patterns.

Troubleshooting

Common Issues

If context usage remains high after optimization, check for large files that were read entirely rather than selectively. If MECW assessments fail, ensure that your environment provides accurate token count metadata. For permission errors when writing output logs to /tmp, verify that the project's temporary directory is writable.