Skills Context and State Management

Each Claude API call is stateless; it does not automatically remember the content of the previous session.

But in a continuous conversation, all historical messages are within the context window. Understanding this helps you write Skills that perform stably in conversations.


Where does Skills state reside?

State type Storage location Validity scope
Conversation history Context window Current session, disappears when closed
Intermediate files /home/claude/ Current session, may be cleared after task completion
Output files /mnt/user-data/outputs/ Persistent, downloadable by user
Installed Skill /mnt/skills/ Cross-session persistence

Skills themselves do not have database or persistent storage capabilities. Data that needs to be saved across sessions should be saved by the user (e.g., downloaded files) or written to a persistent output directory.


Manage multi-turn conversation state in SKILL.md

For Skills that require multi-turn interaction, the flow logic of conversation state should be clearly defined in SKILL.md.

Example

## Multi-turn interaction process

This Skill runs in three stages:

### Stage 1: Information collection
Ask the user to provide the following information:
1. Data file path
2. Analysis goal

Do not perform analysis until all information is obtained.
Display the collected information as a list and tell the user what is still missing.

### Stage 2: Confirmation and execution
After collection is complete, display the execution plan and wait for user confirmation:
>I will{file name}perform{analysis goal}, estimated to take about{time}seconds. Confirm to continue?

### Stage 3: Execute and output
Execute after user confirmation, inform progress in real time, and output the result upon completion.

If the user says at any stage"Restart", clear the currently collected information and return to Stage 1.

Use files to save intermediate state

For complex multi-step tasks, the intermediate state can be written to a JSON file to realize state transfer between steps.

Example

# File path: scripts/state_manager.py
import json
import os
from datetime import datetime

# State file storage path (current session working directory)
STATE_FILE = "/home/claude/skill_state.json"

def save_state(state: dict) -> None:
    """Save current execution state to file"""
    state["updated_at"] = datetime.now().isoformat()
    with open(STATE_FILE, "w", encoding="utf-8") as f:
        json.dump(state, f, ensure_ascii=False, indent=2)
    print(f"State saved: {STATE_FILE}")

def load_state() -> dict:
    """Load the last saved state; return initial state if it does not exist"""
    if not os.path.exists(STATE_FILE):
        return {
            "phase":      "collecting",  # Current phase: collecting / confirming / executing / done
            "file_path":  None,
            "target":     None,
            "result":     None,
            "created_at": datetime.now().isoformat()
        }
    with open(STATE_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def clear_state() -> None:
    """Clear state (for the "Restart" scenario)"""
    if os.path.exists(STATE_FILE):
        os.remove(STATE_FILE)
    print("State cleared, restarting")

# Usage example
if __name__ == "__main__":
    # Load or initialize state
    state = load_state()
    print(f"Current phase: {state['phase']}")

    # Update state: collected file path
    state["file_path"] = "/mnt/user-data/uploads/example_data.csv"
    state["phase"]     = "confirming"
    save_state(state)
状态已保存:/home/claude/skill_state.json
当前阶段:collecting
状态已保存:/home/claude/skill_state.json

Prevent context pollution

When the user triggers a Skill multiple times in the same conversation, old parameters in the conversation history may "pollute" the new execution.

Clearly specifying precedence in SKILL.md can avoid such problems.

Example

## Parameter precedence rules

If multiple sets of parameters exist in the same conversation, handle them according to the following precedence:

1. **Parameters explicitly specified in the user's latest message**→ Highest priority, always use
2. **Files uploaded in this request**→ High priority
3. **Parameters mentioned in conversation history**→ Low priority, use only when not specified in the current message
4. **Default values defined by the Skill**→ Fallback

If there are doubts about the source of the parameters, confirm with the user before execution:"I will use example_v2.csv (the file you just uploaded) instead of the previous example_v1.csv, is that correct?"

Relationship between context length and performance

As the conversation grows longer, the content in the context window increases, and the cost for Claude to process it also increases.

For long-running multi-turn Skills, the following optimization strategies should be noted:

Strategy Method Effect
Avoid repeatedly outputting large chunks of content Reference previously output file paths instead of re-outputting content Reduce context usage
Use files to pass intermediate data Write large datasets to files, and only pass paths in the conversation Avoid having large data fill the context
Promptly inform the user of stage completion After each stage, explicitly say "First step complete" Let the user know progress and reduce follow-up questions

The context window is a limited resource. The larger the amount of data passed in a Skill, the less space remains for reasoning and generation, and response quality may degrade. For large files, always pass via file paths rather than content.

Other extensions