Skill: athola/nm-conserve-context-optimization (version 1.0.2)

--- name: context-optimization description: | Analyze and optimize context window usage with MECW principles, memory tiering, session routing, and subagent coordination version: 1.9.5 metadata: {"openclaw": {"homepage": "https://github.com/athola/claude-night-market/tree/master/plugins/conserve", "emoji": "\ud83e\udd9e"}} source: claude-night-market source_plugin: conserve --- > **Night Market Skill** — ported from [claude-night-market/conserve](https://github.com/athola/claude-night-market/tree/master/plugins/conserve). For the full experience with agents, hooks, and commands, install the Claude Code plugin. ## Table of Contents - [Quick Start](#quick-start) - [When to Use](#when-to-use) - [Core Hub Responsibilities](#core-hub-responsibilities) - [Module Selection Strategy](#module-selection-strategy) - [Context Classification](#context-classification) - [Integration Points](#integration-points) - [Resources](#resources) # 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. ## When NOT To Use - Simple single-step tasks with low context usage - Already using mcp-code-execution for 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 | Utilization | Status | Action | |-------------|--------|--------| | < 30% | LOW | Continue normally | | 30-50% | MODERATE | Monitor, apply principles | | > 50% | CRITICAL | Immediate 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 | Scenario | Before 2.1.2 | After 2.1.2 | |----------|--------------|-------------| | Large test output | Truncated, partial data | Full output via file reference | | Verbose build logs | Lost after 30K chars | Complete, accessible on-demand | | Context pressure | Less from truncation | Same - 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. - **MECW Theory (Extended)**: See `modules/mecw-theory.md` for pressure levels, compliance checking, and monitoring patterns. - **Context Analysis**: See `modules/mecw-assessment.md` for risk identification. - **Workflow Delegation**: See `modules/subagent-coordination.md` for decomposition patterns. - **Context Waiting**: See `modules/context-waiting.md` for deferred loading strategies. ## 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.

path: modules/context-waiting.md
content: # Context Waiting Module

## Overview

Integrates condition-based-waiting principles (bundled in
systematic-debugging since superpowers v4.0.0) with context
optimization to eliminate flaky context monitoring and
resource management.
Replaces arbitrary timeouts with condition polling for
intelligent resource optimization.

## Core Philosophy

**Traditional approach**: `sleep(5)` or `setTimeout(5000)` - guessing at context optimization timing
**Condition-based approach**: Wait for actual optimization completion, resource availability, or context pressure signals

## When to Use

- **Context pressure monitoring**: Wait for actual token threshold breaches
- **Resource optimization completion**: Wait for optimization strategies to complete
- **Async processing**: Wait for background optimization tasks
- **Plugin coordination**: Wait for inter-plugin resource allocations

## Implementation Patterns

### 1. Context Pressure Waiting

```python
#  BEFORE: Arbitrary timeout
time.sleep(2)  # Guess optimization will finish in 2 seconds
context_status = check_context_usage()

#  AFTER: Wait for condition
context_status = wait_for_context_pressure(
    threshold=0.5,
    timeout_ms=5000
)
```

### 2. Optimization Completion Waiting

```python
#  BEFORE: Fixed delay
await asyncio.sleep(3)  # Hope optimization finishes
result = get_optimization_result()

#  AFTER: Wait for completion
result = wait_for_optimization_completion(
    optimization_id=opt_id,
    success_condition=lambda r: r.compression_ratio > 0.3
)
```

### 3. Resource Availability Waiting

```python
#  BEFORE: Poll with sleep
while not resource_available():
    time.sleep(0.5)  # Arbitrary polling interval

#  AFTER: Condition-based polling
wait_for_resource(
    resource_type="memory",
    min_available_mb=100,
    poll_interval_ms=10
)
```

## Waiting Functions

### Core Wait Function

```python
import time
from typing import Callable, Optional, Any

def wait_for_condition(
    condition: Callable[[], Any],
    description: str,
    timeout_ms: int = 5000,
    poll_interval_ms: int = 10
) -> Any:
    """
    Wait for a condition to be met, with timeout and proper error handling.

    Args:
        condition: Function that returns truthy value when condition is met
        description: Human-readable description for error messages
        timeout_ms: Maximum time to wait in milliseconds
        poll_interval_ms: How often to check the condition

    Returns:
        The truthy result from the condition function

    Raises:
        TimeoutError: If condition is not met within timeout
    """
    start_time = time.time()
    timeout_seconds = timeout_ms / 1000
    poll_interval = poll_interval_ms / 1000

    while True:
        result = condition()
        if result:
            return result

        if time.time() - start_time > timeout_seconds:
            raise TimeoutError(
                f"Timeout waiting for {description} after {timeout_ms}ms"
            )

        time.sleep(poll_interval)
```

### Context-Specific Waiting Functions

```python
def wait_for_context_pressure(
    threshold: float = 0.5,
    timeout_ms: int = 10000,
    context_checker: Optional[Callable[[], float]] = None
) -> dict:
    """Wait for context usage to exceed threshold"""

    def condition():
        if context_checker:
            usage = context_checker()
        else:
            usage = get_current_context_usage()
        return usage if usage > threshold else None

    usage = wait_for_condition(
        condition,
        f"context pressure > {threshold}",
        timeout_ms
    )

    return {
        "usage": usage,
        "threshold": threshold,
        "timestamp": time.time()
    }

def wait_for_optimization_completion(
    optimization_id: str,
    success_condition: Optional[Callable[[dict], bool]] = None,
    timeout_ms: int = 30000
) -> dict:
    """Wait for optimization to complete successfully"""

    def condition():
        result = get_optimization_status(optimization_id)
        if result.get("completed"):
            if not success_condition or success_condition(result):
                return result
        return None

    return wait_for_condition(
        condition,
        f"optimization {optimization_id} completion",
        timeout_ms
    )

def wait_for_resource_availability(
    resource_type: str,
    min_required: float,
    resource_checker: Optional[Callable[[], float]] = None,
    timeout_ms: int = 15000
) -> float:
    """Wait for resource to become available"""

    def condition():
        if resource_checker:
            available = resource_checker()
        else:
            available = get_resource_availability(resource_type)
        return available if available >= min_required else None

    return wait_for_condition(
        condition,
        f"{resource_type} >= {min_required}",
        timeout_ms
    )
```

## Integration with Conservation

### Monitoring Context Pressure

```python
class ContextMonitor:
    def __init__(self):
        self.monitoring = False
        self.pressure_handlers = []

    def wait_for_pressure_threshold(
        self,
        threshold: float,
        on_pressure_reached: Optional[Callable] = None
    ) -> dict:
        """Monitor context and wait for threshold breach"""

        def condition():
            usage = self.calculate_context_usage()
            if usage > threshold:
                self.monitoring = False
                if on_pressure_reached:
                    on_pressure_reached(usage)
                return usage
            return None

        self.monitoring = True
        return wait_for_condition(
            condition,
            f"context pressure threshold {threshold}",
            timeout_ms=30000
        )

    def calculate_context_usage(self) -> float:
        """Calculate current context usage as percentage"""
        # Implementation would check actual token usage
        return 0.0  # Placeholder
```

### Coordinating Optimization Tasks

```python
class OptimizationCoordinator:
    def __init__(self):
        self.active_optimizations = {}

    def wait_for_batch_completion(
        self,
        optimization_ids: List[str],
        timeout_ms: int = 60000
    ) -> List[dict]:
        """Wait for multiple optimizations to complete"""

        results = []
        for opt_id in optimization_ids:
            result = wait_for_optimization_completion(
                opt_id,
                timeout_ms=timeout_ms
            )
            results.append(result)

        return results

    def coordinate_with_other_plugins(
        self,
        required_plugins: List[str],
        coordination_timeout_ms: int = 20000
    ) -> dict:
        """Wait for other plugins to be ready for optimization"""

        def condition():
            ready_plugins = []
            for plugin in required_plugins:
                if check_plugin_readiness(plugin):
                    ready_plugins.append(plugin)

            if len(ready_plugins) == len(required_plugins):
                return {"ready": True, "plugins": ready_plugins}
            return None

        return wait_for_condition(
            condition,
            f"plugin coordination: {required_plugins}",
            timeout_ms=coordination_timeout_ms
        )
```

## Examples

### Example 1: Dynamic Context Optimization

```python
# Instead of fixed optimization intervals
def dynamic_optimization_loop():
    while True:
        # Wait for actual pressure, not arbitrary time
        pressure_info = wait_for_context_pressure(threshold=0.6)

        # Optimize based on actual need
        result = optimize_context(
            target_reduction=0.3,
            strategy="priority"
        )

        # Wait for completion before continuing
        wait_for_optimization_completion(
            result["optimization_id"],
            success_condition=lambda r: r["compression_ratio"] > 0.25
        )

        print(f"Optimization completed: {result['compression_ratio']:.2f}")
```

### Example 2: Plugin Resource Coordination

```python
def coordinate_plugin_resources(plugins: List[str]):
    """Coordinate resource usage across multiple plugins"""

    # Wait for all plugins to be ready
    coordination = wait_for_condition(
        lambda: all(check_plugin_ready(p) for p in plugins),
        f"plugin readiness: {plugins}",
        timeout_ms=10000
    )

    # Monitor collective resource usage
    while True:
        total_usage = sum(get_plugin_resource_usage(p) for p in plugins)

        if total_usage > RESOURCE_LIMIT:
            # Trigger optimization across plugins
            optimize_result = wait_for_condition(
                lambda: trigger_collective_optimization(plugins),
                "collective optimization",
                timeout_ms=15000
            )

            # Wait for optimizations to take effect
            wait_for_condition(
                lambda: sum(get_plugin_resource_usage(p) for p in plugins) < RESOURCE_LIMIT,
                "resource usage reduction",
                timeout_ms=10000
            )

        time.sleep(1)  # Normal monitoring interval
```

## Benefits

1. **Eliminates Race Conditions**: No more arbitrary timing guesses
2. **Responsive Optimization**: React to actual conditions, not timers
3. **Resource Efficient**: No wasted polling or unnecessary delays
4. **Better Error Messages**: Clear indication of what was waited for
5. **Testable**: Conditions can be mocked and verified
6. **Composable**: Multiple conditions can be combined

## Best Practices

1. **Always Include Timeouts**: Prevent infinite waiting
2. **Clear Descriptions**: Error messages should explain what was expected
3. **Appropriate Polling**: Default to 10ms, not 1ms (wastes CPU) or 100ms (slows response)
4. **Condition Functions**: Should be fast and side-effect free
5. **Document Conditions**: Explain WHY we're waiting for specific conditions


path: modules/findings-format.md
content: ---
name: findings-format
description: |
  Standard format for agent findings files written to
  .coordination/agents/. Enables selective synthesis
  where the parent reads summaries first.
category: coordination
---

# Agent Findings File Format

Every agent in a coordinated workflow writes its
findings to `.coordination/agents/{name}.findings.md`
using this format.

## Structure

```markdown
---
agent: {agent-name}
area: {codebase-area}
tier: {1|2|3}
evidence_count: {N}
validation_status: {PASS|FAIL|PENDING}
---

## Summary

{1-3 sentences: what was found, overall assessment}

## Detailed Findings

{Full analysis, organized by topic or severity}

[E1] Command: {command run}
     Output: {relevant output}

[E2] Command: {another command}
     Output: {relevant output}

## Evidence

{Evidence log referencing all [EN] tags above}

## Recommendations

{Concrete next steps, ordered by priority}
```

## Selective Synthesis Protocol

When the parent synthesizes multiple findings files:

1. Read ONLY the `## Summary` section from each file
2. Identify high-severity findings across summaries
3. Deep-dive into `## Detailed Findings` only for
   high-severity items
4. Reference raw files for full detail in the report
5. Never copy full findings into parent context

This keeps parent context overhead below 20% while
preserving 100% access to raw findings.

## Frontmatter Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| agent | str | yes | Agent name that produced these findings |
| area | str | no | Codebase area analyzed |
| tier | int | no | Audit tier (1, 2, or 3) |
| evidence_count | int | no | Number of [EN] tags in the file |
| validation_status | str | no | PASS, FAIL, or PENDING |


path: modules/mecw-assessment.md
content: ---
name: mecw-assessment
description: |
  Context usage analysis, risk identification, and optimization
  recommendations for MECW compliance.
category: conservation
---

# MECW Assessment Module

## Overview

This module provides tools and patterns for assessing context usage, identifying risks, and generating optimization recommendations.

## Context Analysis

### Usage Breakdown

```python
def analyze_context_usage(conversation):
    """
    Break down context usage by component.
    """
    return {
        'system_prompt': count_tokens(conversation.system),
        'user_messages': sum(count_tokens(m) for m in conversation.user_msgs),
        'assistant_responses': sum(count_tokens(m) for m in conversation.assistant_msgs),
        'tool_calls': sum(count_tokens(t) for t in conversation.tool_calls),
        'tool_results': sum(count_tokens(r) for r in conversation.tool_results),
    }
```

### Identifying Heavy Consumers

Common context-heavy patterns:
1. **Large file reads**: Reading entire files vs. targeted sections
2. **Verbose tool output**: Full command output vs. summaries
3. **Accumulated history**: Long conversation without compression
4. **Redundant includes**: Same information loaded multiple times

## Risk Identification

### Risk Levels

| Risk Level | Indicators | Action Required |
|------------|------------|-----------------|
| Low | < 30% usage, stable growth | Continue monitoring |
| Medium | 30-45% usage, moderate growth | Plan optimization |
| High | 45-55% usage, rapid growth | Implement optimization |
| Critical | > 55% usage | Immediate intervention |

### Risk Detection

```python
def identify_context_risks(usage_analysis):
    """
    Identify specific risks in current context usage.
    """
    risks = []

    if usage_analysis['tool_results'] > usage_analysis['user_messages'] * 2:
        risks.append({
            'type': 'tool_output_heavy',
            'severity': 'medium',
            'recommendation': 'Summarize tool outputs before storing'
        })

    if usage_analysis['assistant_responses'] > 0.4 * sum(usage_analysis.values()):
        risks.append({
            'type': 'verbose_responses',
            'severity': 'low',
            'recommendation': 'Consider more concise response patterns'
        })

    return risks
```

## Optimization Recommendations

### Content Strategies

1. **Chunking**: Process large files in segments
2. **Filtering**: Extract only relevant sections
3. **Summarization**: Compress completed work
4. **Deduplication**: Remove redundant information

### Implementation Patterns

```python
class OptimizationRecommender:
    def __init__(self, current_usage, target_usage=0.4):
        self.current = current_usage
        self.target = target_usage

    def get_recommendations(self):
        reduction_needed = self.current - self.target

        if reduction_needed <= 0:
            return []

        recommendations = []

        # Priority 1: Tool output compression
        if self._has_heavy_tool_output():
            recommendations.append({
                'action': 'compress_tool_output',
                'priority': 1,
                'estimated_savings': 0.15
            })

        # Priority 2: History summarization
        if self._has_long_history():
            recommendations.append({
                'action': 'summarize_history',
                'priority': 2,
                'estimated_savings': 0.20
            })

        # Priority 3: Subagent delegation
        if self._can_delegate():
            recommendations.append({
                'action': 'delegate_to_subagent',
                'priority': 3,
                'estimated_savings': 0.30
            })

        return recommendations
```

## Compliance Checking

### MECW Compliance Report

```python
def generate_compliance_report(session):
    """
    Generate detailed MECW compliance report.
    """
    usage = analyze_context_usage(session)
    total = sum(usage.values())
    percentage = (total / session.max_context) * 100

    return {
        'compliant': percentage < 50,
        'usage_percentage': percentage,
        'breakdown': usage,
        'risks': identify_context_risks(usage),
        'recommendations': get_recommendations(percentage),
        'trend': calculate_growth_trend(session.history)
    }
```

## Growth Management

### Trend Analysis

- **Stable**: < 5% growth per exchange
- **Growing**: 5-15% growth per exchange
- **Accelerating**: > 15% growth per exchange

### Preemptive Actions

1. **At 30%**: Enable monitoring mode
2. **At 40%**: Start planning optimization
3. **At 45%**: Begin active compression
4. **At 50%**: Trigger emergency protocols

## Integration

- **Principles**: Applies rules from `mecw-principles` module
- **Coordination**: Triggers `subagent-coordination` when needed
- **Conservation**: Works with `token-conservation` for budget management


path: modules/mecw-principles.md
content: ---
name: mecw-principles
description: |
  Maximum Effective Context Window (MECW) theory, the 50% context rule,
  and hallucination prevention fundamentals.
category: conservation
---

# MECW Principles Module

## Overview

This module covers the theoretical foundations of Maximum Effective Context Window (MECW) principles, including the critical 50% rule that prevents hallucinations.

## The 50% Context Rule

**Core Principle**: Never use more than 50% of the *effective* context window for input content.

> **Important (Claude Code 2.1.7+)**: The effective context window is smaller than the total context window because it reserves space for max output tokens. When monitoring context usage, the 50% rule applies to the effective context, not the total. The status line's `used_percentage` field reports usage against the effective context.

### Why 50%?

| Context Usage | Effect on Model |
|---------------|-----------------|
| < 30% | Optimal performance, high accuracy |
| 30-50% | Good performance, slight accuracy degradation |
| 50-70% | Degraded performance, increased hallucination risk |
| > 70% | Severe degradation, high hallucination probability |

### The Physics of Context Pressure

```python
def calculate_context_pressure(current_tokens, max_tokens):
    """
    Context pressure increases non-linearly as usage approaches limits.
    """
    usage_ratio = current_tokens / max_tokens

    if usage_ratio < 0.3:
        return "LOW"      # Plenty of headroom
    elif usage_ratio < 0.5:
        return "MODERATE" # Within MECW limits
    elif usage_ratio < 0.7:
        return "HIGH"     # Exceeding MECW, risk zone
    else:
        return "CRITICAL" # Severe hallucination risk
```

## Hallucination Prevention

### Root Cause
When context exceeds MECW limits:
1. Model attention becomes diffuse across too many tokens
2. Earlier context gets "forgotten" or compressed
3. Model compensates by generating plausible-sounding but incorrect content

### Prevention Strategies

1. **Early Detection**: Monitor context usage continuously
2. **Proactive Compression**: Summarize before hitting limits
3. **Strategic Delegation**: Use subagents for complex workflows
4. **Progressive Disclosure**: Load only needed information

## Practical Application

### Monitoring Context Usage

**Native Visibility (Claude Code 2.0.65+)**: The status line displays context window utilization in real-time, providing immediate visibility into your current usage.

**Improved Accuracy (2.0.70+)**: The `current_usage` field in the status line input enables precise context percentage calculations, eliminating estimation variance.

**Improved Visualization (2.0.74+)**: The `/context` command now groups skills and agents by source plugin, showing:
- Plugin organization and context contribution
- Slash commands in use
- Sorted token counts for optimization
- Better visibility into which plugins consume context

This complements our MECW thresholds:
- **Status line** shows accurate current usage %
- **/context command** shows detailed breakdown by plugin (2.0.74+)

### 1M Context Window (GA, March 2025)

1M tokens is generally available for Opus 4.6 and
Sonnet 4.6 at standard pricing (no long-context premium).

**Default on Max/Team/Enterprise (2.1.75+)**: Opus 4.6
now defaults to 1M context on Max, Team, and Enterprise
plans with no extra usage required. Previously, the 1M
window required extra usage credits. Opt out with
[REDACTED_SECRET]. Media capacity
expands to 600 images or PDF pages (was 100).

MECW thresholds scale proportionally:

| Context Window | 30% (Optimal) | 50% (MECW Limit) | 80% (Emergency) |
|---------------|---------------|-------------------|------------------|
| **200K** | 60K tokens | 100K tokens | 160K tokens |
| **1M** | 300K tokens | 500K tokens | 800K tokens |

> **Note**: The statusline reads `context_window_size`
> dynamically from the Claude Code JSON input, so it
> adapts automatically to whatever window the model
> reports (200K for Sonnet/Haiku, 1M for Opus).

#### Why Conservation Still Matters at 1M

A 1M window full of repeated tool outputs and stale file
reads performs worse than 200K of relevant, structured
state. The performance dropoff at 800-900K tokens still
exists even if less dramatic. Additionally:

- **Quota burn**: Larger context = more input tokens per
  turn = faster quota consumption. Surgical reads and
  selective loading protect your budget.
- **Attention dilution**: Model attention spreads across
  more tokens. Earlier context gets progressively less
  weight. Conservation keeps signal-to-noise high.
- **Agentic compounding**: Parallel agents each accumulate
  tool outputs independently. 5 agents at 200K each can
  collectively burn 1M in tokens while the parent context
  stays lean. Use git worktrees to isolate agent state.

#### The Plan-Clear-Implement Pattern

The 1M window's greatest benefit is enabling large
implementation plans without compaction interruptions:

1. **Plan**: Construct the full implementation plan
   (built-in planning, spec-kit, or similar)
2. **Clear**: `/compact` or `/clear` to start with a
   clean context (built-in planning does this
   automatically before implementation)
3. **Implement**: Execute the plan without compaction,
   maintaining full context of what was done and why
4. **Iterate**: Make follow-up changes while still on
   the same topic with the same context
5. **Repeat**: New plan, new clear, new implementation

This pattern avoids the old cycle of compact, lose
context, re-explore code, repeat instructions. With
discipline, automatic compaction becomes rare.

Server-side compaction (Opus 4.6) provides an additional
safety net: the API automatically summarizes earlier
conversation parts when approaching limits. This does not
replace MECW discipline but reduces catastrophic failure
risk.

### Tool Result Disk Persistence (2.1.51+)

Tool results larger than **50K characters** are now
persisted to disk instead of kept inline in the
conversation context. Previously the threshold was 100K.
This means large tool outputs (file reads, grep results,
web fetches) consume less context window space. Factor
this into MECW calculations: tool-heavy workflows now
have better context longevity than before.

### Compaction Image Preservation (2.1.70+)

Compaction now preserves images in the summarizer
request, allowing prompt cache reuse across compaction
boundaries. This makes compaction faster and cheaper,
especially for image-heavy sessions (screenshots,
diagrams). Previously, images were dropped during
compaction, busting the prompt cache.

### Read Tool Image Safety (2.1.71+)

The Read tool previously put oversized images into
context when image processing failed, breaking
subsequent turns in long image-heavy sessions. Fixed
in 2.1.71: failed image processing no longer injects
oversized data into context. This protects MECW
compliance in sessions that read many images.

### Prompt Cache Fix (2.1.72+)

Fixed prompt cache invalidation in SDK `query()` calls,
reducing input token costs up to 12x for workflows
using the Agent SDK or programmatic Claude Code
invocations. Sessions with heavy SDK usage benefit
most from this fix.

### Resume Token Savings (2.1.70+)

Skill listings are no longer re-injected on every
`--resume` invocation, saving ~600 tokens per resume.
This improves context efficiency for workflows that
frequently resume sessions.

### `/context` Actionable Suggestions (2.1.74+)

The `/context` command now identifies context-heavy
tools, memory bloat, and capacity warnings with specific
optimization tips. Instead of just showing a breakdown,
it recommends actions such as compacting to reclaim
tokens, disabling unused MCP servers, or clearing stale
context. This makes `/context` a diagnostic tool that
directly supports MECW optimization workflows.

Use `/context` at natural breakpoints to get targeted
recommendations rather than manually analyzing the
breakdown.

### Output Style Prompt Cache Improvement (2.1.73+)

`/output-style` is deprecated; use `/config` instead.
Output style is now fixed at session start, preventing
mid-session style changes from invalidating the prompt
cache. This improves cache hit rates for sessions that
previously changed output style between turns. Set your
preferred output style via `/config` before starting
work to maximize cache reuse throughout the session.

### `/compact` Context Exceeded Fix (2.1.85+)

Fixed `/compact` failing when the conversation is too
large for the compact request itself to fit within the
remaining context. Previously a deadlock: compaction
needed most when it could not run. Now handles the edge
case, preventing forced `/clear` with total context loss.

### MCP Tool Description Cap (2.1.84+)

MCP tool descriptions and server instructions capped at
2KB to prevent OpenAPI-generated servers from bloating
context. Duplicate servers (local + claude.ai connectors)
are deduplicated: local config wins. This protects MECW
compliance for sessions using many MCP servers.

### Idle-Return Prompt (2.1.84+)

When returning after 75+ minutes of inactivity, Claude
Code nudges the user to `/clear`. Sessions idle that
long have expired prompt caches, so continued use wastes
tokens re-caching stale context. The nudge supports the
Plan-Clear-Implement pattern.

### System-Prompt Caching Fix (2.1.84+)

Global system-prompt caching now works when ToolSearch
is enabled, including for users with MCP tools. This
improves cache hit rates and reduces input token costs
for sessions loading deferred tools.

### MEMORY.md 25KB Truncation (2.1.83+)

MEMORY.md auto-memory loads the first 200 lines or 25KB
(whichever first) per session. Content beyond the limit
is not injected. Move detailed notes to separate topic
files that are read on demand. CLAUDE.md files are still
loaded in full.

### Progress Message Memory Fix (2.1.77+)

Intermediate progress messages (status updates during
tool execution) were not removed during compaction,
causing unbounded memory growth in long sessions. Now
properly excluded from compacted conversation history.
Critical for egregore orchestration and agent team
workflows that run for extended periods with many tool
invocations.

### Output Token Limit Impact on MECW (2.1.77+)

Opus 4.6 default max output raised to 64k tokens (was
32k). Upper bound raised to 128k for Opus 4.6 and
Sonnet 4.6. Larger output limits reduce the effective
context window available before auto-compaction triggers.
Factor this into MECW calculations: a 128k max output
on a 1M context window means auto-compaction may trigger
at ~870k tokens instead of ~935k.

### Deferred Tools Schema Fix (2.1.76+)

Deferred tools (loaded via `ToolSearch`) previously lost
their input schemas after compaction. The schemas existed
only in conversation context, not in the persistent tool
registry. After compaction, the summarized context no
longer contained raw schemas, causing array and number
parameters to be rejected with type errors. Affected
tools: `CronCreate`, `TaskCreate`, `WebFetch`,
`WebSearch`, `NotebookEdit`, `ExitWorktree`, and MCP
tools. Pre-loaded tools (Bash, Read, Edit, etc.) were
not affected. Schemas are now persisted in the registry
and survive compaction.

### Auto-Compaction Circuit Breaker (2.1.76+)

Auto-compaction previously retried indefinitely after
consecutive failures (API error, timeout, malformed
summary), locking up the session in a compaction loop.
A circuit breaker now stops after 3 consecutive failures.
The session continues without compaction, allowing manual
intervention (`/clear`, `/compact`, or continue working).
The failure counter resets on a successful compaction.

### Context Limit Fix with `model:` Frontmatter (2.1.76+)

Skills with `model:` frontmatter (e.g., `model: sonnet`)
no longer trigger spurious "Context limit reached" on 1M
sessions. The context limit check was using the
frontmatter model's default window (200K for Sonnet)
instead of the session's actual window (1M). Sessions
with >200K tokens loaded would falsely trigger the
check. Now uses the session's actual context window size.

This is particularly relevant for plugin skills using
`model_hint` routing, where skills may temporarily
switch to a different model for execution.

### Token Estimation Fix (2.1.75+)

Fixed token estimation over-counting for `thinking` and
`tool_use` blocks, which triggered premature context
compaction. The estimator inflated the apparent size of
these block types, causing the system to compact earlier
than necessary. Sessions now use more of their available
context window before compaction kicks in.

This is particularly significant for Opus 4.6 with
extended thinking enabled, where thinking blocks can be
substantial. Previous thinking blocks are automatically
stripped from the context window by the API and should
not count toward the active window, but the estimation
bug was including them. Combined with the 1M default
(2.1.75+), this fix means Max/Team/Enterprise users
experience far fewer compaction interruptions.

### JSON-Output Hook Token Savings (2.1.73+)

JSON-output hooks previously injected no-op
system-reminder messages into the model's context on
every turn, wasting tokens. Fixed in 2.1.73: hooks
using JSON output format no longer produce spurious
context injections. Sessions using multiple JSON-output
hooks benefit most from this fix.

**"Summarize from here" (2.1.32+)**: Partial conversation summarization via the message selector provides a manual middle ground between `/compact` (full) and `/new` (clean slate). Use when only older context is stale.
- **Conservation plugin** provides proactive optimization recommendations when approaching thresholds

**Context Optimization with /context (2.0.74+)**:
```bash
# View detailed context breakdown
/context

# Identify high-consuming plugins:
# - Look for plugins with unexpectedly high token counts
# - Check if all loaded skills are actively needed
# - Consider unloading unused plugins to free context

# Example optimization strategy:
# 1. Run /context to see breakdown
# 2. Identify plugins using >10% context
# 3. Evaluate if each plugin's value justifies its context cost
# 4. Unload or defer plugins not needed for current task
```

```python
class MECWMonitor:
    """max_context defaults to 1M (Opus 4.6 GA default)."""
    def __init__(self, max_context=1_000_000):
        self.max_context = max_context
        self.mecw_threshold = max_context * 0.5

    def check_compliance(self, current_tokens):
        if current_tokens > self.mecw_threshold:
            return {
                'compliant': False,
                'overage': current_tokens - self.mecw_threshold,
                'action': 'immediate_optimization_required'
            }
        return {'compliant': True}
```

### Compression Techniques

1. **Code Summarization**: Replace full code with signatures + descriptions
2. **Content Chunking**: Process in MECW-compliant segments
3. **Result Synthesis**: Combine partial results efficiently
4. **Context Rotation**: Swap out completed context for new tasks
5. **LSP Optimization (2.0.74+)**: **Default approach** for token-efficient code navigation
   - **Old grep approach**: Load many files, search text (10,000+ tokens)
   - **LSP approach (PREFERRED)**: Query semantic index, read only target (500 tokens)
   - **Savings**: ~90% token reduction for reference finding
   - **Default strategy**: Always use LSP when available
   - **Enable permanently**: Add `export ENABLE_LSP_TOOL=1` to shell rc
   - **Fallback**: Only use grep when LSP unavailable for language

## Best Practices

1. **Plan for 40%**: Design workflows to use ~40% of context
2. **Buffer for Response**: Leave 50% for model reasoning + response
3. **Monitor Continuously**: Check context at each major step
4. **Fail Fast**: Abort and restructure when approaching limits
5. **Document Aggressively**: Keep summaries for context recovery

## Integration

- **Assessment**: Use with `mecw-assessment` module for analysis
- **Coordination**: Use with `subagent-coordination` for delegation
- **Conservation**: Aligns with `token-conservation` strategies


path: modules/mecw-theory.md
content: # MECW Theory

Maximum Effective Context Window (MECW) theory and patterns for hallucination prevention via context management. Implements the 50% rule.

## Core Principle: The 50% Rule

Context pressure increases non-linearly as usage approaches limits. Exceeding 50% of context window significantly increases hallucination risk.

### Pressure Levels

| Level | Usage | Effect | Action |
|-------|-------|--------|--------|
| **LOW** | <30% | Optimal performance, high accuracy | Continue normally |
| **MODERATE** | 30-50% | Good performance, within MECW | Monitor closely |
| **HIGH** | 50-70% | Degraded performance, risk zone | Optimize immediately |
| **CRITICAL** | >70% | Severe degradation, high hallucination | Reset context |

## Quick Start

### Basic Pressure Check

```python
from leyline import calculate_context_pressure

pressure = calculate_context_pressure(
    current_tokens=80000,
    max_tokens=1000000
)
print(pressure)  # "MODERATE"
```

### Full Compliance Check

```python
from leyline import check_mecw_compliance

result = check_mecw_compliance(
    current_tokens=120000,
    max_tokens=1000000
)

if not result['compliant']:
    print(f"Overage: {result['overage']:,} tokens")
    print(f"Action: {result['action']}")
```

### Continuous Monitoring

```python
from leyline import MECWMonitor

monitor = MECWMonitor(max_context=1000000)
monitor.track_usage(80000)
status = monitor.get_status()

if status.warnings:
    for warning in status.warnings:
        print(f"[WARN] {warning}")
```

## Best Practices

1. **Plan for 40%**: Design workflows to use ~40% of context, leaving buffer
2. **Buffer for Response**: Leave 50% for model reasoning + response generation
3. **Monitor Continuously**: Check context at each major step
4. **Fail Fast**: Abort and restructure when approaching limits
5. **Document Aggressively**: Keep summaries for context recovery after reset

## Detailed Topics

Key implementation areas (consolidated from leyline modules in 1.5.0):
- **Monitoring**: Use `leyline:quota-management` for quota tracking and threshold monitoring
- **Prevention**: Use `leyline:progressive-loading` for budget-aware loading and `conjure:delegation-core` for delegation triggers

## Integration

This module provides foundational MECW utilities referenced by:
- `leyline:progressive-loading` - Uses MECW for budget-aware loading
- `conjure:delegation-core` - Uses MECW for delegation triggers
- Plugin authors building context-aware systems

Reference in your skill's frontmatter:
```yaml
dependencies: [conserve:context-optimization]
```

## Exit Criteria

- Context pressure monitored before major operations
- MECW compliance checked when loading large content
- Safe budget calculated before batch operations
- Recommendations followed when warnings issued
- Context reset triggered before CRITICAL threshold


path: modules/memory-tiers.md
content: ---
name: memory-tiers
description: |
  Three-tier agent memory convention. Hot tier (always
  loaded, 200-line limit), warm tier (on-demand topics),
  cold tier (searchable archive).
category: memory-management
---

# Three-Tier Agent Memory

Long-running or frequently-invoked agents use a tiered
memory hierarchy to keep context lean and prioritized.

## Directory Structure

```
{agent-dir}/
  memory.md          # Hot tier: 200-line limit
  topics/
    validation.md    # Warm tier: on-demand
    patterns.md
  archive/
    2026-02.md       # Cold tier: historical
    2026-03.md
```

## Hot Tier: memory.md

- **Always loaded** at session start
- **200-line hard limit** -- forces prioritization
- Contains: current priorities, active warnings,
  recent decisions, next actions
- Updated every session

## Warm Tier: topics/

- **Pulled on demand** when the agent's task relates
  to a specific topic
- Agent deliberately selects which topics to load
- Includes: research findings, analysis results,
  area-specific patterns
- Updated when new findings are produced

## Cold Tier: archive/

- **Searchable but never auto-loaded**
- Accessed only when investigating past decisions
- Contains: monthly summaries, historical records
- Updated at session end via triage

## Session-End Triage Protocol

At the end of every significant session:

1. Review hot tier for stale content (>1 week old,
   no longer relevant)
2. Demote stale hot-tier content to warm topics
3. Promote urgent warm-tier findings to hot tier
4. Archive old warm-tier content to cold tier
5. Verify hot tier is under 200-line limit

## Why This Works

- The 200-line constraint forces agents to decide
  what matters -- no unbounded accumulation
- Agents control what they remember, not a retrieval
  algorithm
- Warm tier provides depth without context pollution
- Cold tier preserves history without cost
- The file system IS the database -- zero infrastructure

## Integration

- `MemoryManager` class in `scripts/agent_memory.py`
  provides Python API for managing tiers
- Egregore orchestrator can use hot tier for cross-item
  context preservation
- Continuation agents should save state to warm tier
  before handoff


path: modules/session-routing.md
content: ---
name: session-routing
description: |
  Route work to parent context, subagents, or dedicated
  sessions based on complexity. Keeps single-area deep
  work in the parent thread; delegates multi-area work
  to subagents or sessions.
category: coordination
---

# Session Routing

Decide whether work should stay in the parent context,
use subagents, or run in dedicated sessions based on
the number of areas and the nature of the work.

## Routing Rules

| Condition | Route | Reason |
|-----------|-------|--------|
| Single area, deep work | Parent context | No coordination overhead; full context for reasoning and iteration |
| 1-3 areas, focused scope | Subagent | Low coordination overhead, parent context can handle results |
| 4+ areas | Dedicated sessions | Each area needs full context window, parallel subagents degrade |
| Codebase-wide | Sequential sessions | One area at a time, results accumulate in files |

## Decision Logic

```python
from scripts.agent_memory import decide_session_routing

decision = decide_session_routing(
    files=["plugins/imbue/a.py", "plugins/conserve/b.py"],
    areas=["plugins/imbue", "plugins/conserve"],
)
# Returns RoutingDecision.SUBAGENT (2 areas < 4 threshold)
```

## Parent Context Route

- Work stays in the main conversation thread
- No subagent overhead; full context available for
  reasoning, iteration, and follow-up questions
- Best when the task requires deep understanding of
  prior conversation or the user wants to steer
  decisions interactively
- Use when the user explicitly wants to avoid
  subagents or when the work is exploratory

## Subagent Route

- Standard Task tool dispatch
- Each agent gets a tight scope prompt
- Results return through parent context
- Works well for 1-3 focused areas

## Dedicated Session Route

- Use Agent Teams or separate tmux panes
- Each session gets a full clean context window
- Coordinate via `.coordination/` files (see
  findings-format module)
- Parent reads only summaries for synthesis

## Sequential Route

- For codebase-wide operations
- Process one area at a time
- Each session completes before the next begins
- Results accumulate in `.coordination/agents/`
- Final synthesis session reads all findings

## Integration

- `decide_session_routing()` in `scripts/agent_memory.py`
  implements the decision logic
- Integrates with `plan-before-large-dispatch` rule
  (4+ areas trigger plan mode)
- Area-specific context comes from plugin CLAUDE.md
  files and skill descriptions


path: modules/subagent-coordination.md
content: ---
name: subagent-coordination
description: |
  Workflow decomposition and subagent delegation patterns for
  managing context-heavy operations.
category: conservation
---

# Subagent Coordination Module

## Overview

This module provides patterns for decomposing complex workflows and delegating to subagents to maintain MECW compliance.

## Auto-Compaction (Claude Code 2.1.1+)

**Critical Discovery**: Subagent conversations automatically compact when context reaches ~160k tokens.

### How It Works

Claude Code v2.1.1+ introduced automatic context compaction for "sidechain" (subagent) conversations:

```json
{
  "isSidechain": true,
  "agentId": "a2223d9",
  "type": "system",
  "subtype": "compact_boundary",
  "compactMetadata": {
    "trigger": "auto",
    "preTokens": 167189
  }
}
```

**Key observations**:
- **Threshold**: ~160k tokens triggers compaction
- **Automatic**: No configuration needed - system handles it
- **Transparent**: Subagent continues working after compaction
- **Logged**: Check agent logs for `compact_boundary` events

### Implications for Agent Design

1. **Long-running subagents are safe**: They won't crash at context limits
2. **No manual checkpointing needed**: System handles context overflow
3. **Design for continuity**: Ensure subagent state survives compaction
   - Store critical state in files, not just conversation
   - Use explicit progress markers (TodoWrite, checkpoints)
   - Avoid relying on early conversation context for late decisions

### Background Agent Permissions (Claude Code 2.1.20+)

Background agents now **prompt for tool permissions before launching** into the background. This means:

- When a user backgrounds a task (Ctrl+B), permissions are confirmed upfront
- Agents won't stall mid-execution waiting for permission approval
- Multi-agent workflows (e.g., `sanctum:do-issue`) may show permission prompts for each dispatched agent before they begin background work

**Design consideration**: If your workflow dispatches multiple agents in parallel, users will see permission prompts sequentially before agents start. This is expected behavior, not a bug.

### Session Resume Compaction (Claude Code 2.1.20+)

Fixed: `--resume` now correctly loads the compact summary instead of full history. Previously, resumed sessions could reload the entire uncompacted conversation, negating compaction benefits. Subagent state preservation patterns (TodoWrite checkpoints, file-based state) remain the recommended approach since compaction summaries may omit details.

### Task Tool Metrics (Claude Code 2.1.30+)

Task tool results now include **token count**, **tool uses**, and **duration** metrics. This enables data-driven delegation decisions instead of heuristic estimates.

**Key implications**:
- The `should_delegate()` decision framework can now incorporate **actual measured efficiency** from prior Task invocations
- Coordination metrics (line `track_coordination_metrics`) can use native duration instead of manual timing
- Post-execution validation can compare estimated vs. actual token spend per subagent

**Using Task metrics for delegation decisions**:
```python
def should_delegate_with_metrics(task, prior_task_results):
    """Enhanced delegation using real Task tool metrics."""
    # If we have prior data for similar tasks, use actual measurements
    similar = find_similar_prior_results(task, prior_task_results)
    if similar:
        avg_tokens = mean(r.token_count for r in similar)
        avg_duration = mean(r.duration for r in similar)
        efficiency = avg_tokens / (avg_tokens + BASE_OVERHEAD)
        return efficiency >= MIN_EFFICIENCY, f"Measured efficiency: {efficiency:.1%}"

    # Fall back to heuristic estimation for novel tasks
    return should_delegate(task, context_usage)
```

### Improved TaskStop Display (Claude Code 2.1.30+)

TaskStop now shows the **stopped command/task description** instead of a generic "Task stopped" message. This improves debugging of multi-agent workflows — when a subagent is stopped due to context pressure or timeout, you can now identify *which* task was affected without parsing logs.

### Auto-Compact Threshold Fix (Claude Code 2.1.21+)

Fixed: Auto-compact no longer triggers too early on models with large output token limits. Previously, models like Opus (with larger max output) could see compaction trigger significantly below the expected ~160k threshold because the effective context calculation didn't properly account for output token reservation. The thresholds in the table below are now accurate across all model tiers.

### When Auto-Compaction Triggers

| Context Usage | Behavior |
|--------------|----------|
| < 80% (~128k) | Normal operation |
| 80-90% (~128-144k) | Warning zone, plan wrap-up |
| > 90% (~144k+) | Compaction imminent |
| ~160k | **Auto-compaction triggers** |

### Worktree Isolation for Parallel Agents (Claude Code 2.1.49+)

Agents with `isolation: worktree` in their frontmatter run in a temporary git worktree, providing filesystem-level isolation for parallel execution.

- **Parallel safety**: Multiple agents can modify the same files without conflicts — each gets its own working directory
- **Auto-cleanup**: Worktree is removed if the agent makes no changes; preserved with commits if changes exist
- **Frontmatter**: Add `isolation: worktree` to any agent definition, or use `--worktree` CLI flag
- **Background agent constraint**: Agents with `background: true` **cannot use MCP tools or AskUserQuestion** — plan tool access accordingly when combining background execution with worktree isolation
- **First-launch fix (2.1.53+)**: `--worktree` was sometimes silently ignored on first launch — now reliable
- **Config and memory sharing (2.1.63+)**: Project configs and auto-memory are now shared across git worktrees of the same repository. Worktree-isolated agents inherit the parent repo's `.claude/` settings and memory.

### Memory Stability in Long Sessions (Claude Code 2.1.47+)

2.1.47 fixes an O(n^2) message accumulation issue and adds stream buffer release, reducing memory growth in long-running agent sessions. This is particularly relevant for multi-agent workflows where the parent dispatches many sequential subagents — previously, memory usage could grow disproportionately as each subagent's results accumulated. The fix makes sustained orchestration sessions (e.g., large map-reduce pipelines) more stable without requiring manual session restarts.

### Additional Memory Fixes (Claude Code 2.1.50+)

2.1.50 patches several leaks relevant to Task-heavy
workflows: completed TaskOutput and task state objects
are now freed, CircularBuffer no longer retains cleared
items, shell ChildProcess/AbortController references are
released after cleanup, and agent team teammate tasks are
garbage collected on completion. Internal caches are
cleared after compaction, large tool results are freed
after processing, and file history snapshots are capped.
Parallel execution patterns and agent teams are more
viable in long sessions as a result.

### Memory Leak Fixes (Claude Code 2.1.63+)

2.1.63 fixes 12+ memory leak sites: bridge polling,
MCP OAuth cleanup, hooks config menu, permission handler
auto-approvals, bash prefix cache, MCP tool/resource
cache on reconnect, IDE host IP cache, WebSocket
transport reconnect, git root detection cache, JSON
parsing cache, long-running teammate messages in
AppState, and MCP server fetch caches on disconnect.
Heavy progress message payloads are now stripped during
subagent context compaction. Long-running sessions and
multi-agent workflows are significantly more stable.

### Subagent Task State Release (Claude Code 2.1.59+)

2.1.59 releases completed subagent task state from
memory, further reducing RSS growth in Task-heavy
workflows. Combined with the 2.1.50 leak fixes, this
makes sustained multi-agent orchestration sessions more
stable without requiring manual session restarts.

### Tool Result Disk Persistence (Claude Code 2.1.51+)

Tool results larger than 50K characters are persisted to
disk instead of kept inline in conversation context
(previously 100K). This halves the threshold, meaning
more tool outputs are offloaded from the context window.
Subagent-heavy workflows benefit most: each agent's tool
results consume less parent context when aggregated.

### Best Practice: State Preservation

For subagents handling complex, multi-step workflows:

```python
# Pattern: Externalize critical state before compaction risk
def preserve_subagent_state(progress):
    """
    Write state to files so it survives compaction.
    """
    # Write to TodoWrite for task state
    todo_state = {
        'completed': progress.completed_tasks,
        'pending': progress.pending_tasks,
        'context': progress.critical_context
    }

    # Write to temporary file for complex state
    with open('/tmp/subagent_checkpoint.json', 'w') as f:
        json.dump(todo_state, f)

    # Key findings should be in output, not just memory
    return f"Checkpoint saved: {len(progress.completed_tasks)} complete"
```

### Monitoring Auto-Compaction

Check for compaction events in agent logs:

```bash
# Look for compaction boundaries in recent logs
grep -r "compact_boundary" ~/.claude/projects/*/agent_*.log | tail -5
```

## Critical: Subagent Overhead Reality

**Every subagent inherits ~16k+ tokens of system context** (tool definitions, permissions, system prompts) regardless of instruction length. This is the "base overhead" that makes subagents expensive for simple tasks.

### The Economics

| Task Type | Task Tokens | + Base Overhead | Total | Efficiency |
|-----------|-------------|-----------------|-------|------------|
| Simple commit | ~50 | +8,000 | 8,050 | **0.6%** ❌ |
| PR description | ~200 | +8,000 | 8,200 | **2.4%** ❌ |
| Code review | ~3,000 | +8,000 | 11,000 | **27%** ⚠️ |
| Architecture analysis | ~15,000 | +8,000 | 23,000 | **65%** ✅ |
| Multi-file refactor | ~25,000 | +8,000 | 33,000 | **76%** ✅ |

**Rule of Thumb**: If task reasoning < 2,000 tokens, parent agent should do it directly.

### Cost Comparison (Haiku vs Opus)

Even though Haiku is ~60x cheaper per token:
- Parent (Opus) doing simple commit: ~200 tokens = ~$0.009
- Subagent (Haiku) doing simple commit: ~8,700 tokens = ~$0.0065

**Marginal savings ($0.003) don't justify**:
- Latency overhead (subagent spin-up)
- Complexity cost (more failure modes)
- Opportunity cost (8k tokens could fund real reasoning)

## When to Delegate

### CRITICAL: Pre-Invocation Check

**The complexity check MUST happen BEFORE calling the Task tool.**

Once you invoke a subagent, it has already loaded ~8k+ tokens of system context.
A subagent that "bails early" still costs nearly the full overhead.

```
❌ WRONG: Invoke agent → Agent checks complexity → Agent bails → 8k tokens wasted

✅ RIGHT: Parent checks complexity → Skip invocation → 0 tokens spent
```

### Simple Task Threshold

**Before delegating, ask**: "Does this task require analysis, or just execution?"

| Task Type | Reasoning Required | Delegate? |
|-----------|-------------------|-----------|
| `git add && git commit && git push` | None | **NO** - parent does directly |
| "Classify changes and write commit" | Minimal | **NO** - parent does directly |
| "Review PR for security issues" | Substantial | **MAYBE** - if context pressure |
| "Analyze architecture and suggest refactors" | High | **YES** - benefits from fresh context |

### Pre-Invocation Checklist (Parent MUST verify)

Before calling ANY subagent via Task tool:

1. **Can I do this in one command?** → Do it directly
2. **Is the reasoning < 500 tokens?** → Do it directly
3. **Is this a "run X" request?** → Run X directly
4. **Check agent description for ⚠️ PRE-INVOCATION CHECK** → Follow it

### Delegation Triggers (Updated)

| Trigger | Threshold | Action |
|---------|-----------|--------|
| **Task reasoning** | < 2,000 tokens | ❌ Parent does directly |
| Task reasoning | > 2,000 tokens | Consider delegation |
| Context pressure | > 40% usage | Consider delegation |
| Task complexity | > 5 distinct steps | Recommend delegation |
| File operations | > 3 large files | Require delegation |
| Parallel work | Independent subtasks | Optimal for delegation |

### Decision Framework

```python
# Constants
BASE_OVERHEAD = 8000  # System context inherited by every subagent
MIN_EFFICIENCY = 0.20  # 20% minimum efficiency threshold

def should_delegate(task, context_usage):
    """
    Determine if task should be delegated to subagent.

    Key insight: Every subagent inherits ~8k tokens of system context.
    Simple tasks (git commit, file move) waste 99%+ on overhead.
    Only delegate when task reasoning justifies the base cost.
    """
    # FIRST CHECK: Is this a simple execution task?
    if task.estimated_reasoning_tokens < 500:
        return False, "Simple task - parent executes directly"

    # Calculate efficiency
    efficiency = task.estimated_reasoning_tokens / (
        task.estimated_reasoning_tokens + BASE_OVERHEAD
    )

    if efficiency < MIN_EFFICIENCY:
        return False, f"Efficiency {efficiency:.1%} below threshold - parent does it"

    # Context pressure override (delegate even if borderline efficient)
    if context_usage > 0.45:
        return True, "Context pressure requires delegation"

    # Recommended delegation for complex tasks
    if task.estimated_reasoning_tokens > 2000:
        return True, f"Substantial reasoning ({task.estimated_reasoning_tokens} tokens) justifies subagent"

    if task.is_parallelizable and len(task.subtasks) >= 3:
        return True, "Parallel subtasks can run concurrently"

    return False, "Task can be handled in current context"


def estimate_reasoning_tokens(task_description: str) -> int:
    """
    Estimate how many tokens of actual reasoning a task requires.

    Examples:
    - "git add && commit && push" → ~20 tokens (just commands)
    - "Write conventional commit for staged changes" → ~100 tokens
    - "Review PR for security issues" → ~3000 tokens
    - "Analyze architecture and propose refactors" → ~10000 tokens
    """
    # Simple heuristic based on task type
    simple_patterns = ["git add", "git commit", "git push", "mv ", "cp ", "rm "]
    if any(p in task_description.lower() for p in simple_patterns):
        return 50  # Pure execution, minimal reasoning

    analysis_patterns = ["review", "analyze", "evaluate", "assess", "audit"]
    if any(p in task_description.lower() for p in analysis_patterns):
        return 3000  # Substantial reasoning required

    creation_patterns = ["refactor", "implement", "design", "architect"]
    if any(p in task_description.lower() for p in creation_patterns):
        return 5000  # Heavy reasoning required

    return 500  # Default moderate reasoning
```

## Workflow Decomposition

### Breaking Down Complex Tasks

```python
def decompose_workflow(task):
    """
    Break complex task into delegatable units.
    """
    subtasks = []

    # Identify independent components
    for component in task.components:
        if component.has_no_dependencies():
            subtasks.append({
                'type': 'parallel',
                'component': component,
                'can_run_concurrently': True
            })
        else:
            subtasks.append({
                'type': 'sequential',
                'component': component,
                'dependencies': component.dependencies
            })

    return subtasks
```

### Task Packaging

When delegating to a subagent, package:
1. **Clear objective**: What the subagent should accomplish
2. **Required context**: Minimal context needed for the task
3. **Expected output**: Format and content of results
4. **Constraints**: Time limits, resource bounds, quality requirements

## Subagent Patterns

### Pattern 1: Parallel Exploration

```python
# Launch multiple subagents for independent searches
subagents = [
    Task(subagent_type="Explore", prompt="Find auth implementations"),
    Task(subagent_type="Explore", prompt="Find database models"),
    Task(subagent_type="Explore", prompt="Find API endpoints"),
]
# All run concurrently with fresh context each
```

### Pattern 2: Sequential Pipeline

```python
# Chain subagents where each builds on previous
def sequential_pipeline(tasks):
    context = {}
    for task in tasks:
        result = delegate_to_subagent(task, context)
        context.update(result.summary)  # Pass only summary
    return context
```

### Pattern 3: Map-Reduce

```python
# Split large operation, process in parallel, combine results
def map_reduce(files, operation):
    # Map phase: delegate each file to subagent
    results = parallel_delegate([
        {'file': f, 'operation': operation}
        for f in files
    ])

    # Reduce phase: synthesize results
    return synthesize_results(results)
```

## Execution Coordination

### Managing Subagent State

```python
class SubagentCoordinator:
    def __init__(self):
        self.active_subagents = []
        self.results = {}

    def dispatch(self, task_spec):
        """Dispatch task to subagent."""
        subagent_id = launch_subagent(task_spec)
        self.active_subagents.append(subagent_id)
        return subagent_id

    def collect_results(self):
        """
        Collect and synthesize subagent results.

        As of Claude Code 2.1.47, background agents return the final
        answer directly — no transcript parsing needed.
        """
        for subagent_id in self.active_subagents:
            self.results[subagent_id] = get_subagent_result(subagent_id)
        return self.synthesize()

    def synthesize(self):
        """Combine results from all subagents."""
        return {
            'status': 'completed',
            'results': list(self.results.values()),
            'summary': create_summary(self.results)
        }
```

## Result Synthesis

### Combining Subagent Output

1. **Extract key findings**: Pull essential information from each result
2. **Resolve conflicts**: Handle contradictory findings
3. **Build coherent summary**: Create unified view for parent context
4. **Preserve references**: Keep pointers to detailed results if needed

### Synthesis Patterns

```python
def synthesize_exploration_results(results):
    """
    Combine results from parallel exploration subagents.
    """
    synthesis = {
        'files_found': [],
        'patterns_identified': [],
        'recommendations': []
    }

    for result in results:
        synthesis['files_found'].extend(result.get('files', []))
        synthesis['patterns_identified'].extend(result.get('patterns', []))
        synthesis['recommendations'].extend(result.get('recommendations', []))

    # Deduplicate and prioritize
    synthesis['files_found'] = list(set(synthesis['files_found']))
    synthesis['recommendations'] = prioritize(synthesis['recommendations'])

    return synthesis
```

## Agent Teams (Experimental — Claude Code 2.1.32+)

Claude Code 2.1.32 introduces **agent teams** as a research preview for multi-agent collaboration. This is a fundamentally different coordination model from Task-based subagent delegation.

**Enable**: Set `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`

### Agent Teams vs Task Tool

| Aspect | Task Tool (Current) | Agent Teams (Experimental) |
|--------|--------------------|-----------------------------|
| **Coordination** | Parent dispatches, collects results | Lead assigns, teammates message each other |
| **Communication** | One-way (parent→child→result) | Bidirectional (lead↔teammates, teammate↔teammate) |
| **State** | Independent context per subagent | Shared task list, message passing |
| **Parallelism** | Up to 10 concurrent tasks | Lead + multiple teammates |
| **Resume** | Sessions resumable | No resume with in-process teammates |
| **Nesting** | Subagents can spawn subagents | No nested teams |

### When to Use Agent Teams

- Complex multi-step projects where subtasks have **interdependencies**
- Workflows requiring **real-time coordination** between workers
- Situations where one agent's output directly feeds another's input

### When to Stick with Task Tool

- Independent, parallelizable subtasks (map-reduce patterns)
- Simple delegation with clear input→output contracts
- Workflows that need session resumption reliability

### Known Limitations

- **No session resumption**: `/resume` does not restore in-process teammates
- **Task status lag**: Teammates may not mark tasks complete — check manually if stuck
- **One team per session**: Clean up before starting a new team
- **Token-intensive**: Agent teams consume significantly more tokens than Task-based delegation

### Recommendation

Use Task tool patterns for production workflows. Consider agent teams for exploratory, complex coordination scenarios where inter-agent communication adds clear value. Monitor the experimental feature for stabilization before migrating critical workflows.

### Agent Teams Hook Events (Claude Code 2.1.33+)

Two new hook events enable tighter coordination in agent teams workflows:

- **`TeammateIdle`**: Triggered when a teammate agent becomes idle. Use for dynamic work assignment — detect when a teammate finishes and assign new work without polling.
- **`TaskCompleted`**: Triggered when a task finishes execution. Use for pipeline coordination — chain tasks, aggregate results, or trigger follow-up work automatically.

These complement Task tool metrics (2.1.30+) for data-driven orchestration. Example use case: a `TaskCompleted` hook that logs efficiency metrics and triggers the next pipeline stage.

### Sub-Agent Spawning Restrictions (Claude Code 2.1.33+)

Agent `tools` frontmatter now supports `Task(agent_type)` syntax to restrict which sub-agents can be spawned:

```yaml
# Agent can only spawn these specific sub-agents
tools:
  - Read
  - Bash
  - Grep
  - Task(code-reviewer)
  - Task(test-runner)
```

**Benefits**:
- Prevents uncontrolled delegation chains and scope creep
- Enforces pipeline discipline in multi-stage workflows
- Improves security by limiting agent capabilities

**Recommendation**: Add `Task(agent_type)` restrictions to pipeline agents (e.g., `sanctum/workflow-improvement-*`) and orchestrator agents that should only delegate to specific workers. Agents without `Task` in their tools list cannot spawn sub-agents at all — this is already the case for most ecosystem agents.

#### Background Agent Crash Fix (2.1.45+, improved in 2.1.47)

Backgrounded agents (`run_in_background: true`) no longer crash with a ReferenceError on completion. This improves reliability for all parallel dispatch patterns.

- **Before**: Background agents could silently crash, requiring retry logic or manual checking
- **After**: Background agent completion is handled cleanly with proper result delivery
- **2.1.47**: Background agents now return the **final answer directly** instead of raw transcript data (#26012). Previously, collecting results from background agents required parsing through transcript artifacts to extract the actual answer — this workaround is no longer needed. The `collect_results()` pattern in the coordination examples below now receives clean, usable output.

#### Subagent Skill Compaction Fix (2.1.45+)

Skills invoked by subagents no longer leak into the main session's context after compaction.

- **Before**: If a subagent invoked a skill, the skill content could appear in the main session after compaction, consuming context tokens and potentially causing confusion
- **After**: Subagent skill invocations are properly scoped — they stay within the subagent's context and are discarded when the subagent completes
- **Impact**: Long-running sessions with many subagent dispatches will maintain cleaner context

## Best Practices

1. **Minimize handoff context**: Pass only essential information
2. **Define clear boundaries**: Each subagent has specific scope
3. **Plan for failures**: Handle subagent errors gracefully
4. **Summarize aggressively**: Keep only key results
5. **Parallelize when possible**: Use concurrent execution for speed

## Integration

- **Principles**: Follows MECW limits from `mecw-principles`
- **Assessment**: Triggered by risk detection in `mecw-assessment`
- **MCP**: Works with `mcp-code-execution` for code-heavy tasks


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)