home / skills / louloulin / claude-agent-sdk / context-fork-skill

This skill enables running tasks in an isolated forked sub-agent context, preserving separate history and state for complex or experimental workflows.

npx playbooks add skill louloulin/claude-agent-sdk --skill context-fork-skill

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
7.8 KB
---
name: context-fork-skill
description: Demonstrates forked context execution. This skill runs in an isolated sub-agent context with its own conversation history and tool access.
version: "1.0.0"
author: "SDK Team <[email protected]>"
tags:
  - testing
  - subagent
  - isolation
  - context
dependencies: []

context: fork
agent: general-purpose

allowed_tools:
  - Read
  - Write
  - Bash
  - Grep
  - Glob
---

# Context Fork Skill

This skill demonstrates the `context: fork` feature, which allows a skill to run in an isolated sub-agent context with its own conversation history and state.

## What is Forked Context?

When a skill uses `context: fork`, it:

1. **Creates a new sub-agent**: A separate agent instance is created
2. **Isolates conversation history**: Has its own independent context
3. **Provides clean state**: No contamination from the main conversation
4. **Can specify agent type**: Uses the `agent` field to determine sub-agent behavior

## When to Use Forked Context

### ✅ Good Use Cases

1. **Complex Multi-Step Operations**
   - Long-running analyses that shouldn't clutter main conversation
   - Multi-phase processing with intermediate states

2. **Isolated Testing**
   - Test code without affecting main context
   - Experiment with different approaches

3. **Specialized Agent Behavior**
   - Need specific agent type (Plan, Explore, etc.)
   - Different tool access patterns

4. **State Management**
   - Keep temporary state isolated
   - Prevent unintended side effects

### ❌ Avoid When

1. Simple one-shot tasks (overhead not worth it)
2. Need to share results immediately (forked context is isolated)
3. Real-time collaboration required (context is separate)

## Configuration

### Skill Metadata

```yaml
context: fork           # Enables forked context
agent: general-purpose  # Specifies agent type
```

### Available Agent Types

- **general-purpose**: Default agent for general tasks
- **Plan**: Planning and design focused
- **Explore**: Codebase exploration and analysis
- **code-reviewer**: Code review specialist
- **custom**: Custom agents defined in `.claude/agents/`

## Testing Forked Context

### Test 1: Basic Isolation

Ask me to perform a complex analysis:

```
Analyze this codebase and create a detailed report
```

**Behavior**:
1. A new sub-agent is created
2. The analysis runs in isolation
3. The main conversation stays clean
4. Results are returned when complete

### Test 2: Conversation History

Test that the forked context has separate history:

```
First, tell me your name in the forked context
Then ask in the main conversation what we discussed
```

**Expected**: The main conversation won't see the forked context's internal messages

### Test 3: Different Agent Types

Test with different agent types:

```yaml
# For planning tasks
context: fork
agent: Plan

# For exploration
context: fork
agent: Explore

# For code review
context: fork
agent: code-reviewer
```

## Advanced Features

### 1. Combining with Hooks

Forked context works with hooks:

```yaml
context: fork
agent: general-purpose
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "echo 'Forked context: Running Bash'"
```

### 2. Tool Restrictions

Limit tools in forked context:

```yaml
context: fork
agent: general-purpose
allowed_tools:
  - Read
  - Grep
  # No Write - read-only analysis
```

### 3. Model Selection

Use specific model in forked context:

```yaml
context: fork
agent: general-purpose
model: claude-sonnet-4-20250514
```

## Comparison: Forked vs Non-Forked

| Aspect | Non-Forked (Default) | Forked Context |
|--------|---------------------|----------------|
| **Conversation History** | Shared with main | Separate/isolated |
| **State** | Global state | Independent state |
| **Tool Access** | Inherits from main | Configured independently |
| **Context Window** | Uses main context | Separate context window |
| **Overhead** | None | Sub-agent creation |
| **Use Case** | Simple tasks | Complex/isolated tasks |

## Implementation Details

### Architecture

```
Main Conversation
    ↓
    User requests task using context-fork-skill
    ↓
Skill Engine
    ↓
    Detects context: fork
    ↓
Sub-Agent Factory
    ↓
    Creates new agent instance
    ↓
Forked Context
    ↓
    Executes task in isolation
    ↓
    Returns results
    ↓
Main Conversation (receives results)
```

### Memory Considerations

Forked context:
- ✅ Has its own context window
- ✅ Doesn't compete with main context for tokens
- ⚠️ Uses additional memory (sub-agent instance)
- ⚠️ Results still consume tokens when returned

### Performance

Forked context overhead:
- Creation: ~100-200ms
- Execution: Same as normal (no penalty)
- Cleanup: ~50ms

**Total overhead**: ~150-250ms per invocation

## Best Practices

### DO ✅

1. **Use for complex tasks**
   - Multi-step analyses
   - Long-running operations
   - Stateful processing

2. **Choose appropriate agent**
   - Plan for design tasks
   - Explore for code analysis
   - general-purpose for general tasks

3. **Combine with tool restrictions**
   - Read-only for analysis
   - Specific tools for specific tasks

4. **Document the isolation**
   - Explain why forked context is used
   - Clarify what's isolated

### DON'T ❌

1. **Don't use for simple tasks**
   - One-shot queries don't need isolation
   - Adds unnecessary overhead

2. **Don't forget about isolation**
   - Results need to be explicitly returned
   - Can't access main conversation state

3. **Don't overuse**
   - Each fork consumes resources
   - Multiple concurrent forks can be expensive

4. **Don't assume shared state**
   - Forked context starts fresh
   - No memory of previous interactions

## Testing Checklist

Verify forked context behavior:

- [ ] Sub-agent is created
- [ ] Conversation history is isolated
- [ ] Agent type is respected
- [ ] Tool restrictions work
- [ ] Results are returned correctly
- [ ] No contamination of main context
- [ ] Cleanup happens after completion
- [ ] Works with hooks
- [ ] Works with model selection

## Troubleshooting

### Fork Not Creating

**Problem**: Skill runs in main context

**Solutions**:
1. Verify `context: fork` is in YAML frontmatter
2. Check YAML syntax (no tabs, proper indentation)
3. Ensure agent field is specified

### Wrong Agent Type

**Problem**: Uses default agent instead of specified one

**Solutions**:
1. Check agent name spelling
2. Verify agent exists (for custom agents)
3. Use built-in agent names (general-purpose, Plan, Explore)

### Results Not Returned

**Problem**: Forked context completes but no results

**Solutions**:
1. Ensure skill returns output
2. Check for errors in forked context
3. Verify execution completed successfully

## Examples

### Example 1: Code Analysis

```yaml
---
name: deep-code-analysis
description: Perform deep code analysis in isolation
context: fork
agent: Explore
allowed_tools:
  - Read
  - Grep
  - Glob
---
```

**Usage**:
```
Analyze the authentication system deeply
```

### Example 2: Security Audit

```yaml
---
name: security-audit
description: Run security audit in isolated context
context: fork
agent: general-purpose
allowed_tools:
  - Read
  - Grep
  - Bash
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "echo 'Security audit: Executing command'"
---
```

### Example 3: Planning Task

```yaml
---
name: architecture-planner
description: Create architecture plan in isolation
context: fork
agent: Plan
---
```

**Usage**:
```
Create a detailed plan for refactoring the payment system
```

## Summary

Forked context provides:
- ✅ Isolated execution environment
- ✅ Separate conversation history
- ✅ Configurable agent types
- ✅ Clean state management
- ✅ No contamination of main context

Use when you need isolation, complex processing, or specialized agent behavior.

---

**Version**: 1.0.0
**Last Updated**: 2026-01-10
**Maintainer**: SDK Team

Overview

This skill demonstrates forked context execution by running a task inside an isolated sub-agent with its own conversation history and tool access. It shows how to create a separate agent instance, configure agent type, and return results without contaminating the main conversation. Use it to keep complex or stateful work separate from primary interactions.

How this skill works

When invoked with context: fork the skill spawns a sub-agent instance and runs the requested task inside that isolated context. The forked context has an independent conversation history, configurable tools, hooks, and model selection. After execution the fork returns results to the main conversation while leaving main state unchanged.

When to use it

  • Perform multi-step or long-running analyses without cluttering the main conversation
  • Run isolated tests or experiments that must not affect global state
  • Apply specialized agent behavior (Plan, Explore, code-reviewer) for focused tasks
  • Enforce tool restrictions or read-only analysis in a separate environment
  • Maintain temporary state that should not persist in the main agent

Best practices

  • Choose forked context only for tasks that benefit from isolation to avoid unnecessary overhead
  • Pick an appropriate agent type (Plan, Explore, general-purpose) to match the task
  • Limit allowed tools in the fork to reduce surface area and ensure safety
  • Document why the fork is used and what remains isolated so stakeholders understand behavior
  • Return clear, consolidated results to the main conversation since internal forked history is not accessible

Example use cases

  • Deep codebase analysis using an Explore agent with read-only tools
  • Security audit that runs commands and grep inside an isolated context
  • Architecture or migration planning using a Plan agent to produce stepwise deliverables
  • Ad-hoc testing of alternate approaches or code changes without affecting main history
  • Stateful data processing where intermediate state must be discarded after completion

FAQ

Will results from the forked context be visible in the main conversation?

Yes. The fork returns its final output to the main conversation, but intermediate messages and history inside the fork remain isolated.

Does forking add latency or cost?

Forking introduces small overhead for sub-agent creation (roughly 150–250ms total) and uses additional memory; execution time within the fork is comparable to normal runs.

How do I restrict tools inside the fork?

Specify allowed_tools in the fork configuration. Only the listed tools will be available to the sub-agent, enabling read-only or limited access patterns.