Token导航 LogoToken导航

Agent Skill · 研究检索

state-management-patterns(状态管理模式)

state-management-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

state-management-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为执行命令;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 54,235。

总安装 514周安装 21GitHub Stars 23下载 166核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:state-management-patterns(状态管理模式)
来源仓库:https://github.com/akaszubski/autonomous-dev
仓库路径:skills/state-management-patterns
安装命令:
npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patterns

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

state-management-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中根据关键词、任务场景或来源线索快速定位候选结果。它可结合来源仓库、安装命令和原始 README 继续核验具体用法。

安装方式:github,命令为 npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patterns。当前分类为研究检索,适用宿主包括 Codex、Claude、Cursor、Gemini CLI。

安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

来源仓库内路径:skills/state-management-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/akaszubski/autonomous-dev --skill state-manage…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要执行命令,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

state-management-patterns 怎么安装?

在终端执行 npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patte…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

state-management-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

state-management-patterns 需要什么权限?

权限级别是执行命令。安装流程涉及命令执行,可能通过 npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patterns 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

state-management-patterns 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

state-management-patterns 用的人多吗?

公开数据是累计安装 514 次,近一周安装 21 次,下载 166 次,GitHub 23 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

state-management-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要执行命令,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 不能接受 Skill 在你机器上执行命令的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
state-management-patterns

状态管理模式 · 本页

51423执行命令未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

State Management Patterns Skill

Standardized state management and persistence patterns for the autonomous-dev plugin ecosystem. Ensures reliable, crash-resistant state persistence across Claude restarts and system failures.

When This Skill Activates

  • Implementing state persistence
  • Managing crash recovery
  • Handling concurrent state access
  • Versioning state schemas
  • Tracking batch operations
  • Managing user preferences
  • Keywords: "state", "persistence", "JSON", "atomic", "crash recovery", "checkpoint"

Core Patterns

1. JSON Persistence with Atomic Writes

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


2. File Locking for Concurrent Access

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


3. Crash Recovery Pattern

Definition: Design state to enable recovery after crashes or interruptions.

Principles:

  • State includes enough context to resume operations
  • Progress tracking enables "resume from last checkpoint"
  • State validation detects corruption
  • Migration paths handle schema changes

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


4. State Versioning and Migration

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


Real-World Examples

BatchStateManager Pattern

From plugins/autonomous-dev/lib/batch_state_manager.py:

Features:

  • JSON persistence with atomic writes
  • Crash recovery via --resume flag
  • Progress tracking (completed/failed features)
  • Automatic context management via Claude Code (200K token budget)
  • State versioning for schema upgrades

Note (Issue #218): Deprecated context clearing functions (should_clear_context(), pause_batch_for_clear(), get_clear_notification_message()) have been removed as Claude Code v2.0+ handles context automatically with 200K token budget.

Usage:

# Create batch state
state = create_batch_state(features=["feat1", "feat2", "feat3"])
state.batch_id  # "batch-20251116-123456"

# Process features
for feature in state.features:
    try:
        # Process feature
        result = process_feature(feature)
        # Feature implementation updates context automatically

    except Exception as e:
        # Track failures for audit trail
        mark_failed(state, feature, str(e))

    save_batch_state(state_file, state)  # Atomic write

# Resume after crash
state = load_batch_state(state_file)
next_feature = get_next_pending_feature(state)  # Skips completed

Context Management: Claude Code automatically manages the 200K token budget. No manual context clearing required.

Checkpoint Integration (Issue #79)

Agents save checkpoints using the portable pattern:

Portable Pattern (Works Anywhere)

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)")

Features

  • Portable: Works from any directory (user projects, subdirectories, fresh installs)
  • No hardcoded paths: Uses dynamic project root detection
  • Graceful degradation: Returns False, doesn't block workflow
  • Security validated: Path validation (CWE-22), no subprocess (CWE-78)

Design Patterns

  • Progressive Enhancement: Works with or without tracking infrastructure
  • Non-blocking: Never raises exceptions
  • Two-tier: Library imports instead of subprocess calls

See: LIBRARIES.md Section 24 (agent_tracker.py), DEVELOPMENT.md Scenario 2.5, docs/LIBRARIES.md for API


Usage Guidelines

For Library Authors

When implementing stateful features:

  1. Use JSON persistence with atomic writes
  2. Add file locking for concurrent access protection
  3. Design for crash recovery with resumable state
  4. Version your state for schema evolution
  5. Validate on load to detect corruption

For Claude

When creating or analyzing stateful libraries:

  1. Load this skill when keywords match ("state", "persistence", etc.)
  2. Follow persistence patterns for reliability
  3. Implement crash recovery for long-running operations
  4. Use atomic operations to prevent corruption
  5. Reference templates in templates/ directory

Token Savings

By centralizing state management patterns in this skill:

  • Before: ~50 tokens per library for inline state management docs
  • After: ~10 tokens for skill reference comment
  • Savings: ~40 tokens per library
  • Total: ~400 tokens across 10 libraries (4-5% reduction)

Progressive Disclosure

This skill uses Claude Code 2.0+ progressive disclosure architecture:

  • Metadata (frontmatter): Always loaded (~180 tokens)
  • Full content: Loaded only when keywords match
  • Result: Efficient context usage, scales to 100+ skills

When you use terms like "state management", "persistence", "crash recovery", or "atomic writes", Claude Code automatically loads the full skill content.


Templates and Examples

Templates (reusable code structures)

  • templates/state-manager-template.py: Complete state manager class
  • templates/atomic-write-template.py: Atomic write implementation
  • templates/file-lock-template.py: File locking utilities

Examples (real implementations)

  • examples/batch-state-example.py: BatchStateManager pattern
  • examples/user-state-example.py: UserStateManager pattern
  • examples/crash-recovery-example.py: Crash recovery demonstration

Documentation (detailed guides)

  • docs/json-persistence.md: JSON storage patterns
  • docs/atomic-writes.md: Atomic write implementation
  • docs/file-locking.md: Concurrent access protection
  • docs/crash-recovery.md: Recovery strategies

Cross-References

This skill integrates with other autonomous-dev skills:

  • library-design-patterns: Two-tier design, progressive enhancement
  • error-handling-patterns: Exception handling and recovery
  • security-patterns: File permissions and path validation

See: skills/library-design-patterns/, skills/error-handling-patterns/


Maintenance

This skill should be updated when:

  • New state management patterns emerge
  • State schema versioning needs change
  • Concurrency patterns evolve
  • Performance optimizations discovered

Last Updated: 2025-11-16 (Phase 8.8 - Initial creation) Version: 1.0.0


Hard Rules

FORBIDDEN:

  • Storing state without a defined schema or version field
  • Direct file writes without atomic operations (write-then-rename pattern)
  • State files without backup/recovery mechanism
  • Unbounded state growth (MUST have cleanup/rotation strategy)

REQUIRED:

  • All state files MUST include a schema version for migration support
  • State mutations MUST be atomic (no partial writes on failure)
  • State MUST be recoverable from corruption (fallback to defaults)
  • All state access MUST go through a single module (no scattered file reads)

平台分布

Codex

35.61%
按下载量换算59

Claude

30.9%
按下载量换算51

Cursor

17.23%
按下载量换算29

Gemini CLI

8.84%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/akaszubski/autonomous-dev --skill state-management-patterns 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills