State persistence patterns for autonomous-dev including JSON persistence, atomic writes, file locking, crash recovery, and state versioning. Use when implementing stateful libraries or features requiring persistent state.
Provides reliable state persistence patterns including atomic JSON writes, file locking, crash recovery, and state versioning. Use when implementing stateful libraries or features requiring persistent state that survives restarts.
/plugin marketplace add akaszubski/autonomous-dev/plugin install autonomous-dev@autonomous-devThis skill is limited to using the following tools:
docs/atomic-writes.mddocs/crash-recovery.mddocs/file-locking.mddocs/json-persistence.mdexamples/batch-state-example.pyexamples/crash-recovery-example.pyexamples/user-state-example.pytemplates/atomic-write-template.pytemplates/file-lock-template.pytemplates/state-manager-template.pyStandardized state management and persistence patterns for the autonomous-dev plugin ecosystem. Ensures reliable, crash-resistant state persistence across Claude restarts and system failures.
Definition: Store state in JSON files with atomic writes to prevent corruption on crash.
Pattern:
import json
from pathlib import Path
from typing import Dict, Any
import tempfile
import os
def save_state_atomic(state: Dict[str, Any], state_file: Path) -> None:
"""Save state with atomic write to prevent corruption.
Args:
state: State dictionary to persist
state_file: Target state file path
Security:
- Atomic Write: Prevents partial writes on crash
- Temp File: Write to temp, then rename (atomic operation)
- Permissions: Preserves file permissions
"""
# Write to temporary file first
temp_fd, temp_path = tempfile.mkstemp(
dir=state_file.parent,
prefix=f".{state_file.name}.",
suffix=".tmp"
)
try:
# Write JSON to temp file
with os.fdopen(temp_fd, 'w') as f:
json.dump(state, f, indent=2)
# Atomic rename (overwrites target)
os.replace(temp_path, state_file)
except Exception:
# Clean up temp file on failure
if Path(temp_path).exists():
Path(temp_path).unlink()
raise
See: docs/json-persistence.md, examples/batch-state-example.py
Definition: Use file locks to prevent concurrent modification of state files.
Pattern:
import fcntl
import json
from pathlib import Path
from contextlib import contextmanager
@contextmanager
def file_lock(filepath: Path):
"""Acquire exclusive file lock for state file.
Args:
filepath: Path to file to lock
Yields:
Open file handle with exclusive lock
Example:
>>> with file_lock(state_file) as f:
... state = json.load(f)
... state['count'] += 1
... f.seek(0)
... f.truncate()
... json.dump(state, f)
"""
with filepath.open('r+') as f:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
try:
yield f
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
See: docs/file-locking.md, templates/file-lock-template.py
Definition: Design state to enable recovery after crashes or interruptions.
Principles:
Example:
@dataclass
class BatchState:
"""Batch processing state with crash recovery support.
Attributes:
batch_id: Unique batch identifier
features: List of all features to process
current_index: Index of current feature
completed: List of completed feature names
failed: List of failed feature names
created_at: State creation timestamp
last_updated: Last update timestamp
"""
batch_id: str
features: List[str]
current_index: int = 0
completed: List[str] = None
failed: List[str] = None
created_at: str = None
last_updated: str = None
def __post_init__(self):
if self.completed is None:
self.completed = []
if self.failed is None:
self.failed = []
if self.created_at is None:
self.created_at = datetime.now().isoformat()
self.last_updated = datetime.now().isoformat()
See: docs/crash-recovery.md, examples/crash-recovery-example.py
Definition: Version state schemas to enable graceful upgrades.
Pattern:
STATE_VERSION = "2.0.0"
def migrate_state(state: Dict[str, Any]) -> Dict[str, Any]:
"""Migrate state from old version to current.
Args:
state: State dictionary (any version)
Returns:
Migrated state (current version)
"""
version = state.get("version", "1.0.0")
if version == "1.0.0":
# Migrate 1.0.0 → 1.1.0
state = _migrate_1_0_to_1_1(state)
version = "1.1.0"
if version == "1.1.0":
# Migrate 1.1.0 → 2.0.0
state = _migrate_1_1_to_2_0(state)
version = "2.0.0"
state["version"] = STATE_VERSION
return state
See: docs/state-versioning.md, templates/state-manager-template.py
From plugins/autonomous-dev/lib/batch_state_manager.py:
Features:
Usage:
# Create batch state
manager = BatchStateManager.create(["feat1", "feat2", "feat3"])
manager.batch_id # "batch-20251116-123456"
# Process features
for feature in manager.features:
if manager.should_clear_context():
# Clear context at 150K tokens
manager.record_context_clear()
try:
# Process feature
result = process_feature(feature)
manager.mark_completed(feature)
except Exception as e:
manager.mark_failed(feature, str(e))
manager.save() # Atomic write
# Resume after crash
manager = BatchStateManager.load("batch-20251116-123456")
next_feature = manager.get_next_feature() # Skips completed
Agents save checkpoints using the portable pattern:
from pathlib import Path
import sys
# Portable path detection
current = Path.cwd()
while current != current.parent:
if (current / ".git").exists():
project_root = current
break
current = current.parent
# Add lib to path
lib_path = project_root / "plugins/autonomous-dev/lib"
if lib_path.exists():
sys.path.insert(0, str(lib_path))
try:
from agent_tracker import AgentTracker
success = AgentTracker.save_agent_checkpoint(
agent_name='my-agent',
message='Task completed - found 5 patterns',
tools_used=['Read', 'Grep', 'WebSearch']
)
print(f"Checkpoint: {'saved' if success else 'skipped'}")
except ImportError:
print("ℹ️ Checkpoint skipped (user project)")
See: LIBRARIES.md Section 24 (agent_tracker.py), DEVELOPMENT.md Scenario 2.5, docs/LIBRARIES.md for API
When implementing stateful features:
When creating or analyzing stateful libraries:
templates/ directoryBy centralizing state management patterns in this skill:
This skill uses Claude Code 2.0+ progressive disclosure architecture:
When you use terms like "state management", "persistence", "crash recovery", or "atomic writes", Claude Code automatically loads the full skill content.
templates/state-manager-template.py: Complete state manager classtemplates/atomic-write-template.py: Atomic write implementationtemplates/file-lock-template.py: File locking utilitiesexamples/batch-state-example.py: BatchStateManager patternexamples/user-state-example.py: UserStateManager patternexamples/crash-recovery-example.py: Crash recovery demonstrationdocs/json-persistence.md: JSON storage patternsdocs/atomic-writes.md: Atomic write implementationdocs/file-locking.md: Concurrent access protectiondocs/crash-recovery.md: Recovery strategiesThis skill integrates with other autonomous-dev skills:
See: skills/library-design-patterns/, skills/error-handling-patterns/
This skill should be updated when:
Last Updated: 2025-11-16 (Phase 8.8 - Initial creation) Version: 1.0.0
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.