Agent Skills › tzachbon/smart-ralph

tzachbon/smart-ralph

GitHub

指导在 Claude Code 中创建、组织和配置 Slash 命令。涵盖 Markdown 格式、YAML frontmatter 参数、动态参数处理、文件引用及最佳实践,帮助用户构建可复用的自动化工作流。

30 skills 408

Install All Skills

npx skills add tzachbon/smart-ralph --all -g -y
More Options

List skills in collection

npx skills add tzachbon/smart-ralph --list

Skills in Collection (30)

指导在 Claude Code 中创建、组织和配置 Slash 命令。涵盖 Markdown 格式、YAML frontmatter 参数、动态参数处理、文件引用及最佳实践,帮助用户构建可复用的自动化工作流。
创建斜杠命令 添加自定义命令 定义命令参数 使用 YAML frontmatter 组织命令结构 实现交互式命令
.agents/skills/Command Development/SKILL.md
npx skills add tzachbon/smart-ralph --skill Command Development -g -y
SKILL.md
Frontmatter
{
    "name": "Command Development",
    "version": "0.2.0",
    "description": "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."
}

Command Development for Claude Code

Overview

Slash commands are frequently-used prompts defined as Markdown files that Claude executes during interactive sessions. Understanding command structure, frontmatter options, and dynamic features enables creating powerful, reusable workflows.

Key concepts:

  • Markdown file format for commands
  • YAML frontmatter for configuration
  • Dynamic arguments and file references
  • Bash execution for context
  • Command organization and namespacing

Command Basics

What is a Slash Command?

A slash command is a Markdown file containing a prompt that Claude executes when invoked. Commands provide:

  • Reusability: Define once, use repeatedly
  • Consistency: Standardize common workflows
  • Sharing: Distribute across team or projects
  • Efficiency: Quick access to complex prompts

Critical: Commands are Instructions FOR Claude

Commands are written for agent consumption, not human consumption.

When a user invokes /command-name, the command content becomes Claude's instructions. Write commands as directives TO Claude about what to do, not as messages TO the user.

Correct approach (instructions for Claude):

Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication issues

Provide specific line numbers and severity ratings.

Incorrect approach (messages to user):

This command will review your code for security issues.
You'll receive a report with vulnerability details.

The first example tells Claude what to do. The second tells the user what will happen but doesn't instruct Claude. Always use the first approach.

Command Locations

Project commands (shared with team):

  • Location: .claude/commands/
  • Scope: Available in specific project
  • Label: Shown as "(project)" in /help
  • Use for: Team workflows, project-specific tasks

Personal commands (available everywhere):

  • Location: ~/.claude/commands/
  • Scope: Available in all projects
  • Label: Shown as "(user)" in /help
  • Use for: Personal workflows, cross-project utilities

Plugin commands (bundled with plugins):

  • Location: plugin-name/commands/
  • Scope: Available when plugin installed
  • Label: Shown as "(plugin-name)" in /help
  • Use for: Plugin-specific functionality

File Format

Basic Structure

Commands are Markdown files with .md extension:

.claude/commands/
├── review.md           # /review command
├── test.md             # /test command
└── deploy.md           # /deploy command

Simple command:

Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication bypass
- Insecure data handling

No frontmatter needed for basic commands.

With YAML Frontmatter

Add configuration using YAML frontmatter:

---
description: Review code for security issues
allowed-tools: Read, Grep, Bash(git:*)
model: sonnet
---

Review this code for security vulnerabilities...

YAML Frontmatter Fields

description

Purpose: Brief description shown in /help Type: String Default: First line of command prompt

---
description: Review pull request for code quality
---

Best practice: Clear, actionable description (under 60 characters)

allowed-tools

Purpose: Specify which tools command can use Type: String or Array Default: Inherits from conversation

---
allowed-tools: Read, Write, Edit, Bash(git:*)
---

Patterns:

  • Read, Write, Edit - Specific tools
  • Bash(git:*) - Bash with git commands only
  • * - All tools (rarely needed)

Use when: Command requires specific tool access

model

Purpose: Specify model for command execution Type: String (sonnet, opus, haiku) Default: Inherits from conversation

---
model: haiku
---

Use cases:

  • haiku - Fast, simple commands
  • sonnet - Standard workflows
  • opus - Complex analysis

argument-hint

Purpose: Document expected arguments for autocomplete Type: String Default: None

---
argument-hint: [pr-number] [priority] [assignee]
---

Benefits:

  • Helps users understand command arguments
  • Improves command discovery
  • Documents command interface

disable-model-invocation

Purpose: Prevent SlashCommand tool from programmatically calling command Type: Boolean Default: false

---
disable-model-invocation: true
---

Use when: Command should only be manually invoked

Dynamic Arguments

Using $ARGUMENTS

Capture all arguments as single string:

---
description: Fix issue by number
argument-hint: [issue-number]
---

Fix issue #$ARGUMENTS following our coding standards and best practices.

Usage:

> /fix-issue 123
> /fix-issue 456

Expands to:

Fix issue #123 following our coding standards...
Fix issue #456 following our coding standards...

Using Positional Arguments

Capture individual arguments with $1, $2, $3, etc.:

---
description: Review PR with priority and assignee
argument-hint: [pr-number] [priority] [assignee]
---

Review pull request #$1 with priority level $2.
After review, assign to $3 for follow-up.

Usage:

> /review-pr 123 high alice

Expands to:

Review pull request #123 with priority level high.
After review, assign to alice for follow-up.

Combining Arguments

Mix positional and remaining arguments:

Deploy $1 to $2 environment with options: $3

Usage:

> /deploy api staging --force --skip-tests

Expands to:

Deploy api to staging environment with options: --force --skip-tests

File References

Using @ Syntax

Include file contents in command:

---
description: Review specific file
argument-hint: [file-path]
---

Review @$1 for:
- Code quality
- Best practices
- Potential bugs

Usage:

> /review-file src/api/users.ts

Effect: Claude reads src/api/users.ts before processing command

Multiple File References

Reference multiple files:

Compare @src/old-version.js with @src/new-version.js

Identify:
- Breaking changes
- New features
- Bug fixes

Static File References

Reference known files without arguments:

Review @package.json and @tsconfig.json for consistency

Ensure:
- TypeScript version matches
- Dependencies are aligned
- Build configuration is correct

Bash Execution in Commands

Commands can execute bash commands inline to dynamically gather context before Claude processes the command. This is useful for including repository state, environment information, or project-specific context.

When to use:

  • Include dynamic context (git status, environment vars, etc.)
  • Gather project/repository state
  • Build context-aware workflows

Implementation details: For complete syntax, examples, and best practices, see references/plugin-features-reference.md section on bash execution. The reference includes the exact syntax and multiple working examples to avoid execution issues

Command Organization

Flat Structure

Simple organization for small command sets:

.claude/commands/
├── build.md
├── test.md
├── deploy.md
├── review.md
└── docs.md

Use when: 5-15 commands, no clear categories

Namespaced Structure

Organize commands in subdirectories:

.claude/commands/
├── ci/
│   ├── build.md        # /build (project:ci)
│   ├── test.md         # /test (project:ci)
│   └── lint.md         # /lint (project:ci)
├── git/
│   ├── commit.md       # /commit (project:git)
│   └── pr.md           # /pr (project:git)
└── docs/
    ├── generate.md     # /generate (project:docs)
    └── publish.md      # /publish (project:docs)

Benefits:

  • Logical grouping by category
  • Namespace shown in /help
  • Easier to find related commands

Use when: 15+ commands, clear categories

Best Practices

Command Design

  1. Single responsibility: One command, one task
  2. Clear descriptions: Self-explanatory in /help
  3. Explicit dependencies: Use allowed-tools when needed
  4. Document arguments: Always provide argument-hint
  5. Consistent naming: Use verb-noun pattern (review-pr, fix-issue)

Argument Handling

  1. Validate arguments: Check for required arguments in prompt
  2. Provide defaults: Suggest defaults when arguments missing
  3. Document format: Explain expected argument format
  4. Handle edge cases: Consider missing or invalid arguments
---
argument-hint: [pr-number]
---

$IF($1,
  Review PR #$1,
  Please provide a PR number. Usage: /review-pr [number]
)

File References

  1. Explicit paths: Use clear file paths
  2. Check existence: Handle missing files gracefully
  3. Relative paths: Use project-relative paths
  4. Glob support: Consider using Glob tool for patterns

Bash Commands

  1. Limit scope: Use Bash(git:*) not Bash(*)
  2. Safe commands: Avoid destructive operations
  3. Handle errors: Consider command failures
  4. Keep fast: Long-running commands slow invocation

Documentation

  1. Add comments: Explain complex logic
  2. Provide examples: Show usage in comments
  3. List requirements: Document dependencies
  4. Version commands: Note breaking changes
---
description: Deploy application to environment
argument-hint: [environment] [version]
---

<!--
Usage: /deploy [staging|production] [version]
Requires: AWS credentials configured
Example: /deploy staging v1.2.3
-->

Deploy application to $1 environment using version $2...

Common Patterns

Review Pattern

---
description: Review code changes
allowed-tools: Read, Bash(git:*)
---

Files changed: !`git diff --name-only`

Review each file for:
1. Code quality and style
2. Potential bugs or issues
3. Test coverage
4. Documentation needs

Provide specific feedback for each file.

Testing Pattern

---
description: Run tests for specific file
argument-hint: [test-file]
allowed-tools: Bash(npm:*)
---

Run tests: !`npm test $1`

Analyze results and suggest fixes for failures.

Documentation Pattern

---
description: Generate documentation for file
argument-hint: [source-file]
---

Generate comprehensive documentation for @$1 including:
- Function/class descriptions
- Parameter documentation
- Return value descriptions
- Usage examples
- Edge cases and errors

Workflow Pattern

---
description: Complete PR workflow
argument-hint: [pr-number]
allowed-tools: Bash(gh:*), Read
---

PR #$1 Workflow:

1. Fetch PR: !`gh pr view $1`
2. Review changes
3. Run checks
4. Approve or request changes

Troubleshooting

Command not appearing:

  • Check file is in correct directory
  • Verify .md extension present
  • Ensure valid Markdown format
  • Restart Claude Code

Arguments not working:

  • Verify $1, $2 syntax correct
  • Check argument-hint matches usage
  • Ensure no extra spaces

Bash execution failing:

  • Check allowed-tools includes Bash
  • Verify command syntax in backticks
  • Test command in terminal first
  • Check for required permissions

File references not working:

  • Verify @ syntax correct
  • Check file path is valid
  • Ensure Read tool allowed
  • Use absolute or project-relative paths

Plugin-Specific Features

CLAUDE_PLUGIN_ROOT Variable

Plugin commands have access to ${CLAUDE_PLUGIN_ROOT}, an environment variable that resolves to the plugin's absolute path.

Purpose:

  • Reference plugin files portably
  • Execute plugin scripts
  • Load plugin configuration
  • Access plugin templates

Basic usage:

---
description: Analyze using plugin script
allowed-tools: Bash(node:*)
---

Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1`

Review results and report findings.

Common patterns:

# Execute plugin script
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh`

# Load plugin configuration
@${CLAUDE_PLUGIN_ROOT}/config/settings.json

# Use plugin template
@${CLAUDE_PLUGIN_ROOT}/templates/report.md

# Access plugin resources
@${CLAUDE_PLUGIN_ROOT}/docs/reference.md

Why use it:

  • Works across all installations
  • Portable between systems
  • No hardcoded paths needed
  • Essential for multi-file plugins

Plugin Command Organization

Plugin commands discovered automatically from commands/ directory:

plugin-name/
├── commands/
│   ├── foo.md              # /foo (plugin:plugin-name)
│   ├── bar.md              # /bar (plugin:plugin-name)
│   └── utils/
│       └── helper.md       # /helper (plugin:plugin-name:utils)
└── plugin.json

Namespace benefits:

  • Logical command grouping
  • Shown in /help output
  • Avoid name conflicts
  • Organize related commands

Naming conventions:

  • Use descriptive action names
  • Avoid generic names (test, run)
  • Consider plugin-specific prefix
  • Use hyphens for multi-word names

Plugin Command Patterns

Configuration-based pattern:

---
description: Deploy using plugin configuration
argument-hint: [environment]
allowed-tools: Read, Bash(*)
---

Load configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json

Deploy to $1 using configuration settings.
Monitor deployment and report status.

Template-based pattern:

---
description: Generate docs from template
argument-hint: [component]
---

Template: @${CLAUDE_PLUGIN_ROOT}/templates/docs.md

Generate documentation for $1 following template structure.

Multi-script pattern:

---
description: Complete build workflow
allowed-tools: Bash(*)
---

Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh`
Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh`
Package: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh`

Review outputs and report workflow status.

See references/plugin-features-reference.md for detailed patterns.

Integration with Plugin Components

Commands can integrate with other plugin components for powerful workflows.

Agent Integration

Launch plugin agents for complex tasks:

---
description: Deep code review
argument-hint: [file-path]
---

Initiate comprehensive review of @$1 using the code-reviewer agent.

The agent will analyze:
- Code structure
- Security issues
- Performance
- Best practices

Agent uses plugin resources:
- ${CLAUDE_PLUGIN_ROOT}/config/rules.json
- ${CLAUDE_PLUGIN_ROOT}/checklists/review.md

Key points:

  • Agent must exist in plugin/agents/ directory
  • Claude uses Task tool to launch agent
  • Document agent capabilities
  • Reference plugin resources agent uses

Skill Integration

Leverage plugin skills for specialized knowledge:

---
description: Document API with standards
argument-hint: [api-file]
---

Document API in @$1 following plugin standards.

Use the api-docs-standards skill to ensure:
- Complete endpoint documentation
- Consistent formatting
- Example quality
- Error documentation

Generate production-ready API docs.

Key points:

  • Skill must exist in plugin/skills/ directory
  • Mention skill name to trigger invocation
  • Document skill purpose
  • Explain what skill provides

Hook Coordination

Design commands that work with plugin hooks:

  • Commands can prepare state for hooks to process
  • Hooks execute automatically on tool events
  • Commands should document expected hook behavior
  • Guide Claude on interpreting hook output

See references/plugin-features-reference.md for examples of commands that coordinate with hooks

Multi-Component Workflows

Combine agents, skills, and scripts:

---
description: Comprehensive review workflow
argument-hint: [file]
allowed-tools: Bash(node:*), Read
---

Target: @$1

Phase 1 - Static Analysis:
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1`

Phase 2 - Deep Review:
Launch code-reviewer agent for detailed analysis.

Phase 3 - Standards Check:
Use coding-standards skill for validation.

Phase 4 - Report:
Template: @${CLAUDE_PLUGIN_ROOT}/templates/review.md

Compile findings into report following template.

When to use:

  • Complex multi-step workflows
  • Leverage multiple plugin capabilities
  • Require specialized analysis
  • Need structured outputs

Validation Patterns

Commands should validate inputs and resources before processing.

Argument Validation

---
description: Deploy with validation
argument-hint: [environment]
---

Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"`

If $1 is valid environment:
  Deploy to $1
Otherwise:
  Explain valid environments: dev, staging, prod
  Show usage: /deploy [environment]

File Existence Checks

---
description: Process configuration
argument-hint: [config-file]
---

Check file exists: !`test -f $1 && echo "EXISTS" || echo "MISSING"`

If file exists:
  Process configuration: @$1
Otherwise:
  Explain where to place config file
  Show expected format
  Provide example configuration

Plugin Resource Validation

---
description: Run plugin analyzer
allowed-tools: Bash(test:*)
---

Validate plugin setup:
- Script: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"`
- Config: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"`

If all checks pass, run analysis.
Otherwise, report missing components.

Error Handling

---
description: Build with error handling
allowed-tools: Bash(*)
---

Execute build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh 2>&1 || echo "BUILD_FAILED"`

If build succeeded:
  Report success and output location
If build failed:
  Analyze error output
  Suggest likely causes
  Provide troubleshooting steps

Best practices:

  • Validate early in command
  • Provide helpful error messages
  • Suggest corrective actions
  • Handle edge cases gracefully

For detailed frontmatter field specifications, see references/frontmatter-reference.md. For plugin-specific features and patterns, see references/plugin-features-reference.md. For command pattern examples, see examples/ directory.

指导在 Claude Code 插件中集成 Model Context Protocol (MCP) 服务器,支持通过 .mcp.json 或 plugin.json 配置。涵盖 stdio、SSE、HTTP 和 WebSocket 四种连接类型及认证处理,实现外部工具与服务的高效接入。
添加 MCP 服务器 集成 MCP 配置插件中的 MCP 使用 .mcp.json 设置 Model Context Protocol 连接外部服务 提及 ${CLAUDE_PLUGIN_ROOT} 与 MCP 讨论 MCP 服务器类型
.agents/skills/MCP Integration/SKILL.md
npx skills add tzachbon/smart-ralph --skill MCP Integration -g -y
SKILL.md
Frontmatter
{
    "name": "MCP Integration",
    "version": "0.1.0",
    "description": "This skill should be used when the user asks to \"add MCP server\", \"integrate MCP\", \"configure MCP in plugin\", \"use .mcp.json\", \"set up Model Context Protocol\", \"connect external service\", mentions \"${CLAUDE_PLUGIN_ROOT} with MCP\", or discusses MCP server types (SSE, stdio, HTTP, WebSocket). Provides comprehensive guidance for integrating Model Context Protocol servers into Claude Code plugins for external tool and service integration."
}

MCP Integration for Claude Code Plugins

Overview

Model Context Protocol (MCP) enables Claude Code plugins to integrate with external services and APIs by providing structured tool access. Use MCP integration to expose external service capabilities as tools within Claude Code.

Key capabilities:

  • Connect to external services (databases, APIs, file systems)
  • Provide 10+ related tools from a single service
  • Handle OAuth and complex authentication flows
  • Bundle MCP servers with plugins for automatic setup

MCP Server Configuration Methods

Plugins can bundle MCP servers in two ways:

Method 1: Dedicated .mcp.json (Recommended)

Create .mcp.json at plugin root:

{
  "database-tools": {
    "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server",
    "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
    "env": {
      "DB_URL": "${DB_URL}"
    }
  }
}

Benefits:

  • Clear separation of concerns
  • Easier to maintain
  • Better for multiple servers

Method 2: Inline in plugin.json

Add mcpServers field to plugin.json:

{
  "name": "my-plugin",
  "version": "1.0.0",
  "mcpServers": {
    "plugin-api": {
      "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
      "args": ["--port", "8080"]
    }
  }
}

Benefits:

  • Single configuration file
  • Good for simple single-server plugins

MCP Server Types

stdio (Local Process)

Execute local MCP servers as child processes. Best for local tools and custom servers.

Configuration:

{
  "filesystem": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"],
    "env": {
      "LOG_LEVEL": "debug"
    }
  }
}

Use cases:

  • File system access
  • Local database connections
  • Custom MCP servers
  • NPM-packaged MCP servers

Process management:

  • Claude Code spawns and manages the process
  • Communicates via stdin/stdout
  • Terminates when Claude Code exits

SSE (Server-Sent Events)

Connect to hosted MCP servers with OAuth support. Best for cloud services.

Configuration:

{
  "asana": {
    "type": "sse",
    "url": "https://mcp.asana.com/sse"
  }
}

Use cases:

  • Official hosted MCP servers (Asana, GitHub, etc.)
  • Cloud services with MCP endpoints
  • OAuth-based authentication
  • No local installation needed

Authentication:

  • OAuth flows handled automatically
  • User prompted on first use
  • Tokens managed by Claude Code

HTTP (REST API)

Connect to RESTful MCP servers with token authentication.

Configuration:

{
  "api-service": {
    "type": "http",
    "url": "https://api.example.com/mcp",
    "headers": {
      "Authorization": "Bearer ${API_TOKEN}",
      "X-Custom-Header": "value"
    }
  }
}

Use cases:

  • REST API-based MCP servers
  • Token-based authentication
  • Custom API backends
  • Stateless interactions

WebSocket (Real-time)

Connect to WebSocket MCP servers for real-time bidirectional communication.

Configuration:

{
  "realtime-service": {
    "type": "ws",
    "url": "wss://mcp.example.com/ws",
    "headers": {
      "Authorization": "Bearer ${TOKEN}"
    }
  }
}

Use cases:

  • Real-time data streaming
  • Persistent connections
  • Push notifications from server
  • Low-latency requirements

Environment Variable Expansion

All MCP configurations support environment variable substitution:

${CLAUDE_PLUGIN_ROOT} - Plugin directory (always use for portability):

{
  "command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
}

User environment variables - From user's shell:

{
  "env": {
    "API_KEY": "${MY_API_KEY}",
    "DATABASE_URL": "${DB_URL}"
  }
}

Best practice: Document all required environment variables in plugin README.

MCP Tool Naming

When MCP servers provide tools, they're automatically prefixed:

Format: mcp__plugin_<plugin-name>_<server-name>__<tool-name>

Example:

  • Plugin: asana
  • Server: asana
  • Tool: create_task
  • Full name: mcp__plugin_asana_asana__asana_create_task

Using MCP Tools in Commands

Pre-allow specific MCP tools in command frontmatter:

---
allowed-tools: [
  "mcp__plugin_asana_asana__asana_create_task",
  "mcp__plugin_asana_asana__asana_search_tasks"
]
---

Wildcard (use sparingly):

---
allowed-tools: ["mcp__plugin_asana_asana__*"]
---

Best practice: Pre-allow specific tools, not wildcards, for security.

Lifecycle Management

Automatic startup:

  • MCP servers start when plugin enables
  • Connection established before first tool use
  • Restart required for configuration changes

Lifecycle:

  1. Plugin loads
  2. MCP configuration parsed
  3. Server process started (stdio) or connection established (SSE/HTTP/WS)
  4. Tools discovered and registered
  5. Tools available as mcp__plugin_...__...

Viewing servers: Use /mcp command to see all servers including plugin-provided ones.

Authentication Patterns

OAuth (SSE/HTTP)

OAuth handled automatically by Claude Code:

{
  "type": "sse",
  "url": "https://mcp.example.com/sse"
}

User authenticates in browser on first use. No additional configuration needed.

Token-Based (Headers)

Static or environment variable tokens:

{
  "type": "http",
  "url": "https://api.example.com",
  "headers": {
    "Authorization": "Bearer ${API_TOKEN}"
  }
}

Document required environment variables in README.

Environment Variables (stdio)

Pass configuration to MCP server:

{
  "command": "python",
  "args": ["-m", "my_mcp_server"],
  "env": {
    "DATABASE_URL": "${DB_URL}",
    "API_KEY": "${API_KEY}",
    "LOG_LEVEL": "info"
  }
}

Integration Patterns

Pattern 1: Simple Tool Wrapper

Commands use MCP tools with user interaction:

# Command: create-item.md
---
allowed-tools: ["mcp__plugin_name_server__create_item"]
---

Steps:
1. Gather item details from user
2. Use mcp__plugin_name_server__create_item
3. Confirm creation

Use for: Adding validation or preprocessing before MCP calls.

Pattern 2: Autonomous Agent

Agents use MCP tools autonomously:

# Agent: data-analyzer.md

Analysis Process:
1. Query data via mcp__plugin_db_server__query
2. Process and analyze results
3. Generate insights report

Use for: Multi-step MCP workflows without user interaction.

Pattern 3: Multi-Server Plugin

Integrate multiple MCP servers:

{
  "github": {
    "type": "sse",
    "url": "https://mcp.github.com/sse"
  },
  "jira": {
    "type": "sse",
    "url": "https://mcp.jira.com/sse"
  }
}

Use for: Workflows spanning multiple services.

Security Best Practices

Use HTTPS/WSS

Always use secure connections:

✅ "url": "https://mcp.example.com/sse"
❌ "url": "http://mcp.example.com/sse"

Token Management

DO:

  • ✅ Use environment variables for tokens
  • ✅ Document required env vars in README
  • ✅ Let OAuth flow handle authentication

DON'T:

  • ❌ Hardcode tokens in configuration
  • ❌ Commit tokens to git
  • ❌ Share tokens in documentation

Permission Scoping

Pre-allow only necessary MCP tools:

✅ allowed-tools: [
  "mcp__plugin_api_server__read_data",
  "mcp__plugin_api_server__create_item"
]

❌ allowed-tools: ["mcp__plugin_api_server__*"]

Error Handling

Connection Failures

Handle MCP server unavailability:

  • Provide fallback behavior in commands
  • Inform user of connection issues
  • Check server URL and configuration

Tool Call Errors

Handle failed MCP operations:

  • Validate inputs before calling MCP tools
  • Provide clear error messages
  • Check rate limiting and quotas

Configuration Errors

Validate MCP configuration:

  • Test server connectivity during development
  • Validate JSON syntax
  • Check required environment variables

Performance Considerations

Lazy Loading

MCP servers connect on-demand:

  • Not all servers connect at startup
  • First tool use triggers connection
  • Connection pooling managed automatically

Batching

Batch similar requests when possible:

# Good: Single query with filters
tasks = search_tasks(project="X", assignee="me", limit=50)

# Avoid: Many individual queries
for id in task_ids:
    task = get_task(id)

Testing MCP Integration

Local Testing

  1. Configure MCP server in .mcp.json
  2. Install plugin locally (.claude-plugin/)
  3. Run /mcp to verify server appears
  4. Test tool calls in commands
  5. Check claude --debug logs for connection issues

Validation Checklist

  • MCP configuration is valid JSON
  • Server URL is correct and accessible
  • Required environment variables documented
  • Tools appear in /mcp output
  • Authentication works (OAuth or tokens)
  • Tool calls succeed from commands
  • Error cases handled gracefully

Debugging

Enable Debug Logging

claude --debug

Look for:

  • MCP server connection attempts
  • Tool discovery logs
  • Authentication flows
  • Tool call errors

Common Issues

Server not connecting:

  • Check URL is correct
  • Verify server is running (stdio)
  • Check network connectivity
  • Review authentication configuration

Tools not available:

  • Verify server connected successfully
  • Check tool names match exactly
  • Run /mcp to see available tools
  • Restart Claude Code after config changes

Authentication failing:

  • Clear cached auth tokens
  • Re-authenticate
  • Check token scopes and permissions
  • Verify environment variables set

Quick Reference

MCP Server Types

Type Transport Best For Auth
stdio Process Local tools, custom servers Env vars
SSE HTTP Hosted services, cloud APIs OAuth
HTTP REST API backends, token auth Tokens
ws WebSocket Real-time, streaming Tokens

Configuration Checklist

  • Server type specified (stdio/SSE/HTTP/ws)
  • Type-specific fields complete (command or url)
  • Authentication configured
  • Environment variables documented
  • HTTPS/WSS used (not HTTP/WS)
  • ${CLAUDE_PLUGIN_ROOT} used for paths

Best Practices

DO:

  • ✅ Use ${CLAUDE_PLUGIN_ROOT} for portable paths
  • ✅ Document required environment variables
  • ✅ Use secure connections (HTTPS/WSS)
  • ✅ Pre-allow specific MCP tools in commands
  • ✅ Test MCP integration before publishing
  • ✅ Handle connection and tool errors gracefully

DON'T:

  • ❌ Hardcode absolute paths
  • ❌ Commit credentials to git
  • ❌ Use HTTP instead of HTTPS
  • ❌ Pre-allow all tools with wildcards
  • ❌ Skip error handling
  • ❌ Forget to document setup

Additional Resources

Reference Files

For detailed information, consult:

  • references/server-types.md - Deep dive on each server type
  • references/authentication.md - Authentication patterns and OAuth
  • references/tool-usage.md - Using MCP tools in commands and agents

Example Configurations

Working examples in examples/:

  • stdio-server.json - Local stdio MCP server
  • sse-server.json - Hosted SSE server with OAuth
  • http-server.json - REST API with token auth

External Resources

Implementation Workflow

To add MCP integration to a plugin:

  1. Choose MCP server type (stdio, SSE, HTTP, ws)
  2. Create .mcp.json at plugin root with configuration
  3. Use ${CLAUDE_PLUGIN_ROOT} for all file references
  4. Document required environment variables in README
  5. Test locally with /mcp command
  6. Pre-allow MCP tools in relevant commands
  7. Handle authentication (OAuth or tokens)
  8. Test error cases (connection failures, auth errors)
  9. Document MCP integration in plugin README

Focus on stdio for custom/local servers, SSE for hosted services with OAuth.

规范了 Claude Code 插件使用 .claude/plugin-name.local.md 文件存储项目级配置与状态。支持 YAML frontmatter 结构化设置,提供从 Bash hooks、Commands 及 Agents 中读取和解析配置的完整示例与最佳实践。
询问插件配置方法 需要存储用户可配置的插件设置 处理 .local.md 配置文件 读取 YAML frontmatter 数据 实现 per-project 插件行为定制
.agents/skills/Plugin Settings/SKILL.md
npx skills add tzachbon/smart-ralph --skill Plugin Settings -g -y
SKILL.md
Frontmatter
{
    "name": "Plugin Settings",
    "version": "0.1.0",
    "description": "This skill should be used when the user asks about \"plugin settings\", \"store plugin configuration\", \"user-configurable plugin\", \".local.md files\", \"plugin state files\", \"read YAML frontmatter\", \"per-project plugin settings\", or wants to make plugin behavior configurable. Documents the .claude\/plugin-name.local.md pattern for storing plugin-specific configuration with YAML frontmatter and markdown content."
}

Plugin Settings Pattern for Claude Code Plugins

Overview

Plugins can store user-configurable settings and state in .claude/plugin-name.local.md files within the project directory. This pattern uses YAML frontmatter for structured configuration and markdown content for prompts or additional context.

Key characteristics:

  • File location: .claude/plugin-name.local.md in project root
  • Structure: YAML frontmatter + markdown body
  • Purpose: Per-project plugin configuration and state
  • Usage: Read from hooks, commands, and agents
  • Lifecycle: User-managed (not in git, should be in .gitignore)

File Structure

Basic Template

---
enabled: true
setting1: value1
setting2: value2
numeric_setting: 42
list_setting: ["item1", "item2"]
---

# Additional Context

This markdown body can contain:
- Task descriptions
- Additional instructions
- Prompts to feed back to Claude
- Documentation or notes

Example: Plugin State File

.claude/my-plugin.local.md:

---
enabled: true
strict_mode: false
max_retries: 3
notification_level: info
coordinator_session: team-leader
---

# Plugin Configuration

This plugin is configured for standard validation mode.
Contact @team-lead with questions.

Reading Settings Files

From Hooks (Bash Scripts)

Pattern: Check existence and parse frontmatter

#!/bin/bash
set -euo pipefail

# Define state file path
STATE_FILE=".claude/my-plugin.local.md"

# Quick exit if file doesn't exist
if [[ ! -f "$STATE_FILE" ]]; then
  exit 0  # Plugin not configured, skip
fi

# Parse YAML frontmatter (between --- markers)
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$STATE_FILE")

# Extract individual fields
ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//' | sed 's/^"\(.*\)"$/\1/')
STRICT_MODE=$(echo "$FRONTMATTER" | grep '^strict_mode:' | sed 's/strict_mode: *//' | sed 's/^"\(.*\)"$/\1/')

# Check if enabled
if [[ "$ENABLED" != "true" ]]; then
  exit 0  # Disabled
fi

# Use configuration in hook logic
if [[ "$STRICT_MODE" == "true" ]]; then
  # Apply strict validation
  # ...
fi

See examples/read-settings-hook.sh for complete working example.

From Commands

Commands can read settings files to customize behavior:

---
description: Process data with plugin
allowed-tools: ["Read", "Bash"]
---

# Process Command

Steps:
1. Check if settings exist at `.claude/my-plugin.local.md`
2. Read configuration using Read tool
3. Parse YAML frontmatter to extract settings
4. Apply settings to processing logic
5. Execute with configured behavior

From Agents

Agents can reference settings in their instructions:

---
name: configured-agent
description: Agent that adapts to project settings
---

Check for plugin settings at `.claude/my-plugin.local.md`.
If present, parse YAML frontmatter and adapt behavior according to:
- enabled: Whether plugin is active
- mode: Processing mode (strict, standard, lenient)
- Additional configuration fields

Parsing Techniques

Extract Frontmatter

# Extract everything between --- markers
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$FILE")

Read Individual Fields

String fields:

VALUE=$(echo "$FRONTMATTER" | grep '^field_name:' | sed 's/field_name: *//' | sed 's/^"\(.*\)"$/\1/')

Boolean fields:

ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//')
# Compare: if [[ "$ENABLED" == "true" ]]; then

Numeric fields:

MAX=$(echo "$FRONTMATTER" | grep '^max_value:' | sed 's/max_value: *//')
# Use: if [[ $MAX -gt 100 ]]; then

Read Markdown Body

Extract content after second ---:

# Get everything after closing ---
BODY=$(awk '/^---$/{i++; next} i>=2' "$FILE")

Common Patterns

Pattern 1: Temporarily Active Hooks

Use settings file to control hook activation:

#!/bin/bash
STATE_FILE=".claude/security-scan.local.md"

# Quick exit if not configured
if [[ ! -f "$STATE_FILE" ]]; then
  exit 0
fi

# Read enabled flag
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$STATE_FILE")
ENABLED=$(echo "$FRONTMATTER" | grep '^enabled:' | sed 's/enabled: *//')

if [[ "$ENABLED" != "true" ]]; then
  exit 0  # Disabled
fi

# Run hook logic
# ...

Use case: Enable/disable hooks without editing hooks.json (requires restart).

Pattern 2: Agent State Management

Store agent-specific state and configuration:

.claude/multi-agent-swarm.local.md:

---
agent_name: auth-agent
task_number: 3.5
pr_number: 1234
coordinator_session: team-leader
enabled: true
dependencies: ["Task 3.4"]
---

# Task Assignment

Implement JWT authentication for the API.

**Success Criteria:**
- Authentication endpoints created
- Tests passing
- PR created and CI green

Read from hooks to coordinate agents:

AGENT_NAME=$(echo "$FRONTMATTER" | grep '^agent_name:' | sed 's/agent_name: *//')
COORDINATOR=$(echo "$FRONTMATTER" | grep '^coordinator_session:' | sed 's/coordinator_session: *//')

# Send notification to coordinator
tmux send-keys -t "$COORDINATOR" "Agent $AGENT_NAME completed task" Enter

Pattern 3: Configuration-Driven Behavior

.claude/my-plugin.local.md:

---
validation_level: strict
max_file_size: 1000000
allowed_extensions: [".js", ".ts", ".tsx"]
enable_logging: true
---

# Validation Configuration

Strict mode enabled for this project.
All writes validated against security policies.

Use in hooks or commands:

LEVEL=$(echo "$FRONTMATTER" | grep '^validation_level:' | sed 's/validation_level: *//')

case "$LEVEL" in
  strict)
    # Apply strict validation
    ;;
  standard)
    # Apply standard validation
    ;;
  lenient)
    # Apply lenient validation
    ;;
esac

Creating Settings Files

From Commands

Commands can create settings files:

# Setup Command

Steps:
1. Ask user for configuration preferences
2. Create `.claude/my-plugin.local.md` with YAML frontmatter
3. Set appropriate values based on user input
4. Inform user that settings are saved
5. Remind user to restart Claude Code for hooks to recognize changes

Template Generation

Provide template in plugin README:

## Configuration

Create `.claude/my-plugin.local.md` in your project:

\`\`\`markdown
---
enabled: true
mode: standard
max_retries: 3
---

# Plugin Configuration

Your settings are active.
\`\`\`

After creating or editing, restart Claude Code for changes to take effect.

Best Practices

File Naming

DO:

  • Use .claude/plugin-name.local.md format
  • Match plugin name exactly
  • Use .local.md suffix for user-local files

DON'T:

  • Use different directory (not .claude/)
  • Use inconsistent naming
  • Use .md without .local (might be committed)

Gitignore

Always add to .gitignore:

.claude/*.local.md
.claude/*.local.json

Document this in plugin README.

Defaults

Provide sensible defaults when settings file doesn't exist:

if [[ ! -f "$STATE_FILE" ]]; then
  # Use defaults
  ENABLED=true
  MODE=standard
else
  # Read from file
  # ...
fi

Validation

Validate settings values:

MAX=$(echo "$FRONTMATTER" | grep '^max_value:' | sed 's/max_value: *//')

# Validate numeric range
if ! [[ "$MAX" =~ ^[0-9]+$ ]] || [[ $MAX -lt 1 ]] || [[ $MAX -gt 100 ]]; then
  echo "⚠️  Invalid max_value in settings (must be 1-100)" >&2
  MAX=10  # Use default
fi

Restart Requirement

Important: Settings changes require Claude Code restart.

Document in your README:

## Changing Settings

After editing `.claude/my-plugin.local.md`:
1. Save the file
2. Exit Claude Code
3. Restart: `claude` or `cc`
4. New settings will be loaded

Hooks cannot be hot-swapped within a session.

Security Considerations

Sanitize User Input

When writing settings files from user input:

# Escape quotes in user input
SAFE_VALUE=$(echo "$USER_INPUT" | sed 's/"/\\"/g')

# Write to file
cat > "$STATE_FILE" <<EOF
---
user_setting: "$SAFE_VALUE"
---
EOF

Validate File Paths

If settings contain file paths:

FILE_PATH=$(echo "$FRONTMATTER" | grep '^data_file:' | sed 's/data_file: *//')

# Check for path traversal
if [[ "$FILE_PATH" == *".."* ]]; then
  echo "⚠️  Invalid path in settings (path traversal)" >&2
  exit 2
fi

Permissions

Settings files should be:

  • Readable by user only (chmod 600)
  • Not committed to git
  • Not shared between users

Real-World Examples

multi-agent-swarm Plugin

.claude/multi-agent-swarm.local.md:

---
agent_name: auth-implementation
task_number: 3.5
pr_number: 1234
coordinator_session: team-leader
enabled: true
dependencies: ["Task 3.4"]
additional_instructions: Use JWT tokens, not sessions
---

# Task: Implement Authentication

Build JWT-based authentication for the REST API.
Coordinate with auth-agent on shared types.

Hook usage (agent-stop-notification.sh):

  • Checks if file exists (line 15-18: quick exit if not)
  • Parses frontmatter to get coordinator_session, agent_name, enabled
  • Sends notifications to coordinator if enabled
  • Allows quick activation/deactivation via enabled: true/false

ralph-wiggum Plugin

.claude/ralph-loop.local.md:

---
iteration: 1
max_iterations: 10
completion_promise: "All tests passing and build successful"
---

Fix all the linting errors in the project.
Make sure tests pass after each fix.

Hook usage (stop-hook.sh):

  • Checks if file exists (line 15-18: quick exit if not active)
  • Reads iteration count and max_iterations
  • Extracts completion_promise for loop termination
  • Reads body as the prompt to feed back
  • Updates iteration count on each loop

Quick Reference

File Location

project-root/
└── .claude/
    └── plugin-name.local.md

Frontmatter Parsing

# Extract frontmatter
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$FILE")

# Read field
VALUE=$(echo "$FRONTMATTER" | grep '^field:' | sed 's/field: *//' | sed 's/^"\(.*\)"$/\1/')

Body Parsing

# Extract body (after second ---)
BODY=$(awk '/^---$/{i++; next} i>=2' "$FILE")

Quick Exit Pattern

if [[ ! -f ".claude/my-plugin.local.md" ]]; then
  exit 0  # Not configured
fi

Additional Resources

Reference Files

For detailed implementation patterns:

  • references/parsing-techniques.md - Complete guide to parsing YAML frontmatter and markdown bodies
  • references/real-world-examples.md - Deep dive into multi-agent-swarm and ralph-wiggum implementations

Example Files

Working examples in examples/:

  • read-settings-hook.sh - Hook that reads and uses settings
  • create-settings-command.md - Command that creates settings file
  • example-settings.md - Template settings file

Utility Scripts

Development tools in scripts/:

  • validate-settings.sh - Validate settings file structure
  • parse-frontmatter.sh - Extract frontmatter fields

Implementation Workflow

To add settings to a plugin:

  1. Design settings schema (which fields, types, defaults)
  2. Create template file in plugin documentation
  3. Add gitignore entry for .claude/*.local.md
  4. Implement settings parsing in hooks/commands
  5. Use quick-exit pattern (check file exists, check enabled field)
  6. Document settings in plugin README with template
  7. Remind users that changes require Claude Code restart

Focus on keeping settings simple and providing good defaults when settings file doesn't exist.

指导如何创建、组织和配置 Claude Code 插件。涵盖目录结构规范、plugin.json 清单文件设置、组件(命令/代理/技能)布局及自动发现机制,帮助开发者构建标准化且可维护的插件架构。
创建或脚手架化插件 理解插件目录结构 配置 plugin.json 清单 组织插件组件和文件命名 使用 CLAUDE_PLUGIN_ROOT 路径
.agents/skills/Plugin Structure/SKILL.md
npx skills add tzachbon/smart-ralph --skill Plugin Structure -g -y
SKILL.md
Frontmatter
{
    "name": "Plugin Structure",
    "version": "0.1.0",
    "description": "This skill should be used when the user asks to \"create a plugin\", \"scaffold a plugin\", \"understand plugin structure\", \"organize plugin components\", \"set up plugin.json\", \"use ${CLAUDE_PLUGIN_ROOT}\", \"add commands\/agents\/skills\/hooks\", \"configure auto-discovery\", or needs guidance on plugin directory layout, manifest configuration, component organization, file naming conventions, or Claude Code plugin architecture best practices."
}

Plugin Structure for Claude Code

Overview

Claude Code plugins follow a standardized directory structure with automatic component discovery. Understanding this structure enables creating well-organized, maintainable plugins that integrate seamlessly with Claude Code.

Key concepts:

  • Conventional directory layout for automatic discovery
  • Manifest-driven configuration in .claude-plugin/plugin.json
  • Component-based organization (commands, agents, skills, hooks)
  • Portable path references using ${CLAUDE_PLUGIN_ROOT}
  • Explicit vs. auto-discovered component loading

Directory Structure

Every Claude Code plugin follows this organizational pattern:

plugin-name/
├── .claude-plugin/
│   └── plugin.json          # Required: Plugin manifest
├── commands/                 # Slash commands (.md files)
├── agents/                   # Subagent definitions (.md files)
├── skills/                   # Agent skills (subdirectories)
│   └── skill-name/
│       └── SKILL.md         # Required for each skill
├── hooks/
│   └── hooks.json           # Event handler configuration
├── .mcp.json                # MCP server definitions
└── scripts/                 # Helper scripts and utilities

Critical rules:

  1. Manifest location: The plugin.json manifest MUST be in .claude-plugin/ directory
  2. Component locations: All component directories (commands, agents, skills, hooks) MUST be at plugin root level, NOT nested inside .claude-plugin/
  3. Optional components: Only create directories for components the plugin actually uses
  4. Naming convention: Use kebab-case for all directory and file names

Plugin Manifest (plugin.json)

The manifest defines plugin metadata and configuration. Located at .claude-plugin/plugin.json:

Required Fields

{
  "name": "plugin-name"
}

Name requirements:

  • Use kebab-case format (lowercase with hyphens)
  • Must be unique across installed plugins
  • No spaces or special characters
  • Example: code-review-assistant, test-runner, api-docs

Recommended Metadata

{
  "name": "plugin-name",
  "version": "1.0.0",
  "description": "Brief explanation of plugin purpose",
  "author": {
    "name": "Author Name",
    "email": "author@example.com",
    "url": "https://example.com"
  },
  "homepage": "https://docs.example.com",
  "repository": "https://github.com/user/plugin-name",
  "license": "MIT",
  "keywords": ["testing", "automation", "ci-cd"]
}

Version format: Follow semantic versioning (MAJOR.MINOR.PATCH) Keywords: Use for plugin discovery and categorization

Component Path Configuration

Specify custom paths for components (supplements default directories):

{
  "name": "plugin-name",
  "commands": "./custom-commands",
  "agents": ["./agents", "./specialized-agents"],
  "hooks": "./config/hooks.json",
  "mcpServers": "./.mcp.json"
}

Important: Custom paths supplement defaults—they don't replace them. Components in both default directories and custom paths will load.

Path rules:

  • Must be relative to plugin root
  • Must start with ./
  • Cannot use absolute paths
  • Support arrays for multiple locations

Component Organization

Commands

Location: commands/ directory Format: Markdown files with YAML frontmatter Auto-discovery: All .md files in commands/ load automatically

Example structure:

commands/
├── review.md        # /review command
├── test.md          # /test command
└── deploy.md        # /deploy command

File format:

---
name: command-name
description: Command description
---

Command implementation instructions...

Usage: Commands integrate as native slash commands in Claude Code

Agents

Location: agents/ directory Format: Markdown files with YAML frontmatter Auto-discovery: All .md files in agents/ load automatically

Example structure:

agents/
├── code-reviewer.md
├── test-generator.md
└── refactorer.md

File format:

---
description: Agent role and expertise
capabilities:
  - Specific task 1
  - Specific task 2
---

Detailed agent instructions and knowledge...

Usage: Users can invoke agents manually, or Claude Code selects them automatically based on task context

Skills

Location: skills/ directory with subdirectories per skill Format: Each skill in its own directory with SKILL.md file Auto-discovery: All SKILL.md files in skill subdirectories load automatically

Example structure:

skills/
├── api-testing/
│   ├── SKILL.md
│   ├── scripts/
│   │   └── test-runner.py
│   └── references/
│       └── api-spec.md
└── database-migrations/
    ├── SKILL.md
    └── examples/
        └── migration-template.sql

SKILL.md format:

---
name: Skill Name
description: When to use this skill
version: 1.0.0
---

Skill instructions and guidance...

Supporting files: Skills can include scripts, references, examples, or assets in subdirectories

Usage: Claude Code autonomously activates skills based on task context matching the description

Hooks

Location: hooks/hooks.json or inline in plugin.json Format: JSON configuration defining event handlers Registration: Hooks register automatically when plugin enables

Example structure:

hooks/
├── hooks.json           # Hook configuration
└── scripts/
    ├── validate.sh      # Hook script
    └── check-style.sh   # Hook script

Configuration format:

{
  "PreToolUse": [{
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "command",
      "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/validate.sh",
      "timeout": 30
    }]
  }]
}

Available events: PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification

Usage: Hooks execute automatically in response to Claude Code events

MCP Servers

Location: .mcp.json at plugin root or inline in plugin.json Format: JSON configuration for MCP server definitions Auto-start: Servers start automatically when plugin enables

Example format:

{
  "mcpServers": {
    "server-name": {
      "command": "node",
      "args": ["${CLAUDE_PLUGIN_ROOT}/servers/server.js"],
      "env": {
        "API_KEY": "${API_KEY}"
      }
    }
  }
}

Usage: MCP servers integrate seamlessly with Claude Code's tool system

Portable Path References

${CLAUDE_PLUGIN_ROOT}

Use ${CLAUDE_PLUGIN_ROOT} environment variable for all intra-plugin path references:

{
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/run.sh"
}

Why it matters: Plugins install in different locations depending on:

  • User installation method (marketplace, local, npm)
  • Operating system conventions
  • User preferences

Where to use it:

  • Hook command paths
  • MCP server command arguments
  • Script execution references
  • Resource file paths

Never use:

  • Hardcoded absolute paths (/Users/name/plugins/...)
  • Relative paths from working directory (./scripts/... in commands)
  • Home directory shortcuts (~/plugins/...)

Path Resolution Rules

In manifest JSON fields (hooks, MCP servers):

"command": "${CLAUDE_PLUGIN_ROOT}/scripts/tool.sh"

In component files (commands, agents, skills):

Reference scripts at: ${CLAUDE_PLUGIN_ROOT}/scripts/helper.py

In executed scripts:

#!/bin/bash
# ${CLAUDE_PLUGIN_ROOT} available as environment variable
source "${CLAUDE_PLUGIN_ROOT}/lib/common.sh"

File Naming Conventions

Component Files

Commands: Use kebab-case .md files

  • code-review.md/code-review
  • run-tests.md/run-tests
  • api-docs.md/api-docs

Agents: Use kebab-case .md files describing role

  • test-generator.md
  • code-reviewer.md
  • performance-analyzer.md

Skills: Use kebab-case directory names

  • api-testing/
  • database-migrations/
  • error-handling/

Supporting Files

Scripts: Use descriptive kebab-case names with appropriate extensions

  • validate-input.sh
  • generate-report.py
  • process-data.js

Documentation: Use kebab-case markdown files

  • api-reference.md
  • migration-guide.md
  • best-practices.md

Configuration: Use standard names

  • hooks.json
  • .mcp.json
  • plugin.json

Auto-Discovery Mechanism

Claude Code automatically discovers and loads components:

  1. Plugin manifest: Reads .claude-plugin/plugin.json when plugin enables
  2. Commands: Scans commands/ directory for .md files
  3. Agents: Scans agents/ directory for .md files
  4. Skills: Scans skills/ for subdirectories containing SKILL.md
  5. Hooks: Loads configuration from hooks/hooks.json or manifest
  6. MCP servers: Loads configuration from .mcp.json or manifest

Discovery timing:

  • Plugin installation: Components register with Claude Code
  • Plugin enable: Components become available for use
  • No restart required: Changes take effect on next Claude Code session

Override behavior: Custom paths in plugin.json supplement (not replace) default directories

Best Practices

Organization

  1. Logical grouping: Group related components together

    • Put test-related commands, agents, and skills together
    • Create subdirectories in scripts/ for different purposes
  2. Minimal manifest: Keep plugin.json lean

    • Only specify custom paths when necessary
    • Rely on auto-discovery for standard layouts
    • Use inline configuration only for simple cases
  3. Documentation: Include README files

    • Plugin root: Overall purpose and usage
    • Component directories: Specific guidance
    • Script directories: Usage and requirements

Naming

  1. Consistency: Use consistent naming across components

    • If command is test-runner, name related agent test-runner-agent
    • Match skill directory names to their purpose
  2. Clarity: Use descriptive names that indicate purpose

    • Good: api-integration-testing/, code-quality-checker.md
    • Avoid: utils/, misc.md, temp.sh
  3. Length: Balance brevity with clarity

    • Commands: 2-3 words (review-pr, run-ci)
    • Agents: Describe role clearly (code-reviewer, test-generator)
    • Skills: Topic-focused (error-handling, api-design)

Portability

  1. Always use ${CLAUDE_PLUGIN_ROOT}: Never hardcode paths
  2. Test on multiple systems: Verify on macOS, Linux, Windows
  3. Document dependencies: List required tools and versions
  4. Avoid system-specific features: Use portable bash/Python constructs

Maintenance

  1. Version consistently: Update version in plugin.json for releases
  2. Deprecate gracefully: Mark old components clearly before removal
  3. Document breaking changes: Note changes affecting existing users
  4. Test thoroughly: Verify all components work after changes

Common Patterns

Minimal Plugin

Single command with no dependencies:

my-plugin/
├── .claude-plugin/
│   └── plugin.json    # Just name field
└── commands/
    └── hello.md       # Single command

Full-Featured Plugin

Complete plugin with all component types:

my-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/          # User-facing commands
├── agents/            # Specialized subagents
├── skills/            # Auto-activating skills
├── hooks/             # Event handlers
│   ├── hooks.json
│   └── scripts/
├── .mcp.json          # External integrations
└── scripts/           # Shared utilities

Skill-Focused Plugin

Plugin providing only skills:

my-plugin/
├── .claude-plugin/
│   └── plugin.json
└── skills/
    ├── skill-one/
    │   └── SKILL.md
    └── skill-two/
        └── SKILL.md

Troubleshooting

Component not loading:

  • Verify file is in correct directory with correct extension
  • Check YAML frontmatter syntax (commands, agents, skills)
  • Ensure skill has SKILL.md (not README.md or other name)
  • Confirm plugin is enabled in Claude Code settings

Path resolution errors:

  • Replace all hardcoded paths with ${CLAUDE_PLUGIN_ROOT}
  • Verify paths are relative and start with ./ in manifest
  • Check that referenced files exist at specified paths
  • Test with echo $CLAUDE_PLUGIN_ROOT in hook scripts

Auto-discovery not working:

  • Confirm directories are at plugin root (not in .claude-plugin/)
  • Check file naming follows conventions (kebab-case, correct extensions)
  • Verify custom paths in manifest are correct
  • Restart Claude Code to reload plugin configuration

Conflicts between plugins:

  • Use unique, descriptive component names
  • Namespace commands with plugin name if needed
  • Document potential conflicts in plugin README
  • Consider command prefixes for related functionality

For detailed examples and advanced patterns, see files in references/ and examples/ directories.

指导为 Claude Code 插件创建、改进和组织技能。涵盖技能结构、YAML元数据编写、资源组织及最佳实践,旨在将通用代理转化为具备特定领域工作流和工具集成能力的专用代理。
创建新技能 向插件添加技能 改进技能描述 组织技能内容 寻求技能开发最佳实践
.agents/skills/Skill Development/SKILL.md
npx skills add tzachbon/smart-ralph --skill Skill Development -g -y
SKILL.md
Frontmatter
{
    "name": "Skill Development",
    "version": "0.1.0",
    "description": "This skill should be used when the user wants to \"create a skill\", \"add a skill to plugin\", \"write a new skill\", \"improve skill description\", \"organize skill content\", or needs guidance on skill structure, progressive disclosure, or skill development best practices for Claude Code plugins."
}

Skill Development for Claude Code Plugins

This skill provides guidance for creating effective skills for Claude Code plugins.

About Skills

Skills are modular, self-contained packages that extend Claude's capabilities by providing specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains or tasks—they transform Claude from a general-purpose agent into a specialized agent equipped with procedural knowledge that no model can fully possess.

What Skills Provide

  1. Specialized workflows - Multi-step procedures for specific domains
  2. Tool integrations - Instructions for working with specific file formats or APIs
  3. Domain expertise - Company-specific knowledge, schemas, business logic
  4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks

Anatomy of a Skill

Every skill consists of a required SKILL.md file and optional bundled resources:

skill-name/
├── SKILL.md (required)
│   ├── YAML frontmatter metadata (required)
│   │   ├── name: (required)
│   │   └── description: (required)
│   └── Markdown instructions (required)
└── Bundled Resources (optional)
    ├── scripts/          - Executable code (Python/Bash/etc.)
    ├── references/       - Documentation intended to be loaded into context as needed
    └── assets/           - Files used in output (templates, icons, fonts, etc.)

SKILL.md (required)

Metadata Quality: The name and description in YAML frontmatter determine when Claude will use the skill. Be specific about what the skill does and when to use it. Use the third-person (e.g. "This skill should be used when..." instead of "Use this skill when...").

Bundled Resources (optional)

Scripts (scripts/)

Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.

  • When to include: When the same code is being rewritten repeatedly or deterministic reliability is needed
  • Example: scripts/rotate_pdf.py for PDF rotation tasks
  • Benefits: Token efficient, deterministic, may be executed without loading into context
  • Note: Scripts may still need to be read by Claude for patching or environment-specific adjustments
References (references/)

Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.

  • When to include: For documentation that Claude should reference while working
  • Examples: references/finance.md for financial schemas, references/mnda.md for company NDA template, references/policies.md for company policies, references/api_docs.md for API specifications
  • Use cases: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
  • Benefits: Keeps SKILL.md lean, loaded only when Claude determines it's needed
  • Best practice: If files are large (>10k words), include grep search patterns in SKILL.md
  • Avoid duplication: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
Assets (assets/)

Files not intended to be loaded into context, but rather used within the output Claude produces.

  • When to include: When the skill needs files that will be used in the final output
  • Examples: assets/logo.png for brand assets, assets/slides.pptx for PowerPoint templates, assets/frontend-template/ for HTML/React boilerplate, assets/font.ttf for typography
  • Use cases: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
  • Benefits: Separates output resources from documentation, enables Claude to use files without loading them into context

Progressive Disclosure Design Principle

Skills use a three-level loading system to manage context efficiently:

  1. Metadata (name + description) - Always in context (~100 words)
  2. SKILL.md body - When skill triggers (<5k words)
  3. Bundled resources - As needed by Claude (Unlimited*)

*Unlimited because scripts can be executed without reading into context window.

Skill Creation Process

To create a skill, follow the "Skill Creation Process" in order, skipping steps only if there is a clear reason why they are not applicable.

Step 1: Understanding the Skill with Concrete Examples

Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.

To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.

For example, when building an image-editor skill, relevant questions include:

  • "What functionality should the image-editor skill support? Editing, rotating, anything else?"
  • "Can you give some examples of how this skill would be used?"
  • "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
  • "What would a user say that should trigger this skill?"

To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.

Conclude this step when there is a clear sense of the functionality the skill should support.

Step 2: Planning the Reusable Skill Contents

To turn concrete examples into an effective skill, analyze each example by:

  1. Considering how to execute on the example from scratch
  2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly

Example: When building a pdf-editor skill to handle queries like "Help me rotate this PDF," the analysis shows:

  1. Rotating a PDF requires re-writing the same code each time
  2. A scripts/rotate_pdf.py script would be helpful to store in the skill

Example: When designing a frontend-webapp-builder skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:

  1. Writing a frontend webapp requires the same boilerplate HTML/React each time
  2. An assets/hello-world/ template containing the boilerplate HTML/React project files would be helpful to store in the skill

Example: When building a big-query skill to handle queries like "How many users have logged in today?" the analysis shows:

  1. Querying BigQuery requires re-discovering the table schemas and relationships each time
  2. A references/schema.md file documenting the table schemas would be helpful to store in the skill

For Claude Code plugins: When building a hooks skill, the analysis shows:

  1. Developers repeatedly need to validate hooks.json and test hook scripts
  2. scripts/validate-hook-schema.sh and scripts/test-hook.sh utilities would be helpful
  3. references/patterns.md for detailed hook patterns to avoid bloating SKILL.md

To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.

Step 3: Create Skill Structure

For Claude Code plugins, create the skill directory structure:

mkdir -p plugin-name/skills/skill-name/{references,examples,scripts}
touch plugin-name/skills/skill-name/SKILL.md

Note: Unlike the generic skill-creator which uses init_skill.py, plugin skills are created directly in the plugin's skills/ directory with a simpler manual structure.

Step 4: Edit the Skill

When editing the (newly-created or existing) skill, remember that the skill is being created for another instance of Claude to use. Focus on including information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.

Start with Reusable Skill Contents

To begin implementation, start with the reusable resources identified above: scripts/, references/, and assets/ files. Note that this step may require user input. For example, when implementing a brand-guidelines skill, the user may need to provide brand assets or templates to store in assets/, or documentation to store in references/.

Also, delete any example files and directories not needed for the skill. Create only the directories you actually need (references/, examples/, scripts/).

Update SKILL.md

Writing Style: Write the entire skill using imperative/infinitive form (verb-first instructions), not second person. Use objective, instructional language (e.g., "To accomplish X, do Y" rather than "You should do X" or "If you need to do X"). This maintains consistency and clarity for AI consumption.

Description (Frontmatter): Use third-person format with specific trigger phrases:

---
name: Skill Name
description: This skill should be used when the user asks to "specific phrase 1", "specific phrase 2", "specific phrase 3". Include exact phrases users would say that should trigger this skill. Be concrete and specific.
version: 0.1.0
---

Good description examples:

description: This skill should be used when the user asks to "create a hook", "add a PreToolUse hook", "validate tool use", "implement prompt-based hooks", or mentions hook events (PreToolUse, PostToolUse, Stop).

Bad description examples:

description: Use this skill when working with hooks.  # Wrong person, vague
description: Load when user needs hook help.  # Not third person
description: Provides hook guidance.  # No trigger phrases

To complete SKILL.md body, answer the following questions:

  1. What is the purpose of the skill, in a few sentences?
  2. When should the skill be used? (Include this in frontmatter description with specific triggers)
  3. In practice, how should Claude use the skill? All reusable skill contents developed above should be referenced so that Claude knows how to use them.

Keep SKILL.md lean: Target 1,500-2,000 words for the body. Move detailed content to references/:

  • Detailed patterns → references/patterns.md
  • Advanced techniques → references/advanced.md
  • Migration guides → references/migration.md
  • API references → references/api-reference.md

Reference resources in SKILL.md:

## Additional Resources

### Reference Files

For detailed patterns and techniques, consult:
- **`references/patterns.md`** - Common patterns
- **`references/advanced.md`** - Advanced use cases

### Example Files

Working examples in `examples/`:
- **`example-script.sh`** - Working example

Step 5: Validate and Test

For plugin skills, validation is different from generic skills:

  1. Check structure: Skill directory in plugin-name/skills/skill-name/
  2. Validate SKILL.md: Has frontmatter with name and description
  3. Check trigger phrases: Description includes specific user queries
  4. Verify writing style: Body uses imperative/infinitive form, not second person
  5. Test progressive disclosure: SKILL.md is lean (~1,500-2,000 words), detailed content in references/
  6. Check references: All referenced files exist
  7. Validate examples: Examples are complete and correct
  8. Test scripts: Scripts are executable and work correctly

Use the skill-reviewer agent:

Ask: "Review my skill and check if it follows best practices"

The skill-reviewer agent will check description quality, content organization, and progressive disclosure.

Step 6: Iterate

After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.

Iteration workflow:

  1. Use the skill on real tasks
  2. Notice struggles or inefficiencies
  3. Identify how SKILL.md or bundled resources should be updated
  4. Implement changes and test again

Common improvements:

  • Strengthen trigger phrases in description
  • Move long sections from SKILL.md to references/
  • Add missing examples or scripts
  • Clarify ambiguous instructions
  • Add edge case handling

Plugin-Specific Considerations

Skill Location in Plugins

Plugin skills live in the plugin's skills/ directory:

my-plugin/
├── .claude-plugin/
│   └── plugin.json
├── commands/
├── agents/
└── skills/
    └── my-skill/
        ├── SKILL.md
        ├── references/
        ├── examples/
        └── scripts/

Auto-Discovery

Claude Code automatically discovers skills:

  • Scans skills/ directory
  • Finds subdirectories containing SKILL.md
  • Loads skill metadata (name + description) always
  • Loads SKILL.md body when skill triggers
  • Loads references/examples when needed

No Packaging Needed

Plugin skills are distributed as part of the plugin, not as separate ZIP files. Users get skills when they install the plugin.

Testing in Plugins

Test skills by installing plugin locally:

# Test with --plugin-dir
cc --plugin-dir /path/to/plugin

# Ask questions that should trigger the skill
# Verify skill loads correctly

Examples from Plugin-Dev

Study the skills in this plugin as examples of best practices:

hook-development skill:

  • Excellent trigger phrases: "create a hook", "add a PreToolUse hook", etc.
  • Lean SKILL.md (1,651 words)
  • 3 references/ files for detailed content
  • 3 examples/ of working hooks
  • 3 scripts/ utilities

agent-development skill:

  • Strong triggers: "create an agent", "agent frontmatter", etc.
  • Focused SKILL.md (1,438 words)
  • References include the AI generation prompt from Claude Code
  • Complete agent examples

plugin-settings skill:

  • Specific triggers: "plugin settings", ".local.md files", "YAML frontmatter"
  • References show real implementations (multi-agent-swarm, ralph-wiggum)
  • Working parsing scripts

Each demonstrates progressive disclosure and strong triggering.

Progressive Disclosure in Practice

What Goes in SKILL.md

Include (always loaded when skill triggers):

  • Core concepts and overview
  • Essential procedures and workflows
  • Quick reference tables
  • Pointers to references/examples/scripts
  • Most common use cases

Keep under 3,000 words, ideally 1,500-2,000 words

What Goes in references/

Move to references/ (loaded as needed):

  • Detailed patterns and advanced techniques
  • Comprehensive API documentation
  • Migration guides
  • Edge cases and troubleshooting
  • Extensive examples and walkthroughs

Each reference file can be large (2,000-5,000+ words)

What Goes in examples/

Working code examples:

  • Complete, runnable scripts
  • Configuration files
  • Template files
  • Real-world usage examples

Users can copy and adapt these directly

What Goes in scripts/

Utility scripts:

  • Validation tools
  • Testing helpers
  • Parsing utilities
  • Automation scripts

Should be executable and documented

Writing Style Requirements

Imperative/Infinitive Form

Write using verb-first instructions, not second person:

Correct (imperative):

To create a hook, define the event type.
Configure the MCP server with authentication.
Validate settings before use.

Incorrect (second person):

You should create a hook by defining the event type.
You need to configure the MCP server.
You must validate settings before use.

Third-Person in Description

The frontmatter description must use third person:

Correct:

description: This skill should be used when the user asks to "create X", "configure Y"...

Incorrect:

description: Use this skill when you want to create X...
description: Load this skill when user asks...

Objective, Instructional Language

Focus on what to do, not who should do it:

Correct:

Parse the frontmatter using sed.
Extract fields with grep.
Validate values before use.

Incorrect:

You can parse the frontmatter...
Claude should extract fields...
The user might validate values...

Validation Checklist

Before finalizing a skill:

Structure:

  • SKILL.md file exists with valid YAML frontmatter
  • Frontmatter has name and description fields
  • Markdown body is present and substantial
  • Referenced files actually exist

Description Quality:

  • Uses third person ("This skill should be used when...")
  • Includes specific trigger phrases users would say
  • Lists concrete scenarios ("create X", "configure Y")
  • Not vague or generic

Content Quality:

  • SKILL.md body uses imperative/infinitive form
  • Body is focused and lean (1,500-2,000 words ideal, <5k max)
  • Detailed content moved to references/
  • Examples are complete and working
  • Scripts are executable and documented

Progressive Disclosure:

  • Core concepts in SKILL.md
  • Detailed docs in references/
  • Working code in examples/
  • Utilities in scripts/
  • SKILL.md references these resources

Testing:

  • Skill triggers on expected user queries
  • Content is helpful for intended tasks
  • No duplicated information across files
  • References load when needed

Common Mistakes to Avoid

Mistake 1: Weak Trigger Description

Bad:

description: Provides guidance for working with hooks.

Why bad: Vague, no specific trigger phrases, not third person

Good:

description: This skill should be used when the user asks to "create a hook", "add a PreToolUse hook", "validate tool use", or mentions hook events. Provides comprehensive hooks API guidance.

Why good: Third person, specific phrases, concrete scenarios

Mistake 2: Too Much in SKILL.md

Bad:

skill-name/
└── SKILL.md  (8,000 words - everything in one file)

Why bad: Bloats context when skill loads, detailed content always loaded

Good:

skill-name/
├── SKILL.md  (1,800 words - core essentials)
└── references/
    ├── patterns.md (2,500 words)
    └── advanced.md (3,700 words)

Why good: Progressive disclosure, detailed content loaded only when needed

Mistake 3: Second Person Writing

Bad:

You should start by reading the configuration file.
You need to validate the input.
You can use the grep tool to search.

Why bad: Second person, not imperative form

Good:

Start by reading the configuration file.
Validate the input before processing.
Use the grep tool to search for patterns.

Why good: Imperative form, direct instructions

Mistake 4: Missing Resource References

Bad:

# SKILL.md

[Core content]

[No mention of references/ or examples/]

Why bad: Claude doesn't know references exist

Good:

# SKILL.md

[Core content]

## Additional Resources

### Reference Files
- **`references/patterns.md`** - Detailed patterns
- **`references/advanced.md`** - Advanced techniques

### Examples
- **`examples/script.sh`** - Working example

Why good: Claude knows where to find additional information

Quick Reference

Minimal Skill

skill-name/
└── SKILL.md

Good for: Simple knowledge, no complex resources needed

Standard Skill (Recommended)

skill-name/
├── SKILL.md
├── references/
│   └── detailed-guide.md
└── examples/
    └── working-example.sh

Good for: Most plugin skills with detailed documentation

Complete Skill

skill-name/
├── SKILL.md
├── references/
│   ├── patterns.md
│   └── advanced.md
├── examples/
│   ├── example1.sh
│   └── example2.json
└── scripts/
    └── validate.sh

Good for: Complex domains with validation utilities

Best Practices Summary

DO:

  • Use third-person in description ("This skill should be used when...")
  • Include specific trigger phrases ("create X", "configure Y")
  • Keep SKILL.md lean (1,500-2,000 words)
  • Use progressive disclosure (move details to references/)
  • Write in imperative/infinitive form
  • Reference supporting files clearly
  • Provide working examples
  • Create utility scripts for common operations
  • Study plugin-dev's skills as templates

DON'T:

  • Use second person anywhere
  • Have vague trigger conditions
  • Put everything in SKILL.md (>3,000 words without references/)
  • Write in second person ("You should...")
  • Leave resources unreferenced
  • Include broken or incomplete examples
  • Skip validation

Additional Resources

Study These Skills

Plugin-dev's skills demonstrate best practices:

  • ../hook-development/ - Progressive disclosure, utilities
  • ../agent-development/ - AI-assisted creation, references
  • ../mcp-integration/ - Comprehensive references
  • ../plugin-settings/ - Real-world examples
  • ../command-development/ - Clear critical concepts
  • ../plugin-structure/ - Good organization

Reference Files

For complete skill-creator methodology:

  • references/skill-creator-original.md - Full original skill-creator content

Implementation Workflow

To create a skill for your plugin:

  1. Understand use cases: Identify concrete examples of skill usage
  2. Plan resources: Determine what scripts/references/examples needed
  3. Create structure: mkdir -p skills/skill-name/{references,examples,scripts}
  4. Write SKILL.md:
    • Frontmatter with third-person description and trigger phrases
    • Lean body (1,500-2,000 words) in imperative form
    • Reference supporting files
  5. Add resources: Create references/, examples/, scripts/ as needed
  6. Validate: Check description, writing style, organization
  7. Test: Verify skill loads on expected triggers
  8. Iterate: Improve based on usage

Focus on strong trigger descriptions, progressive disclosure, and imperative writing style for effective skills that load when needed and provide targeted guidance.

定义AI代理的沟通风格规范,要求极致简洁、易扫描、可操作。遵循Matt Pocock规划原则,强调省略语法以换取精简,优先使用片段、表格和列表。输出结构需包含概述、主体、待解问题及最后列出的具体行动步骤,旨在降低Token成本并提升终端阅读效率。
需要生成计划或技术方案时 编写代码实现说明时 进行系统架构设计讨论时
plugins/ralph-speckit/skills/communication-style/SKILL.md
npx skills add tzachbon/smart-ralph --skill communication-style -g -y
SKILL.md
Frontmatter
{
    "name": "communication-style",
    "version": "0.1.0",
    "description": "Output rules for all agents - concise, scannable, actionable. Based on Matt Pocock's planning principles."
}

Communication Style

Core Rule

Be extremely concise. Sacrifice grammar for concision.

Why

  • Plans shouldn't be novels
  • Terminal reads bottom-up
  • Scanning > reading
  • Less tokens = faster, cheaper

Output Rules

1. Brevity First

Instead of Write
"The user will be able to..." "User can..."
"This component is responsible for..." "Handles..."
"In order to achieve this, we need to..." "Requires:"
"It should be noted that..." (delete)

Use:

  • Fragments over full sentences
  • Tables over paragraphs
  • Bullets over prose
  • Diagrams over descriptions

2. Structure for Scanning

Every output follows this order:

1. Brief overview (2-3 sentences MAX)
2. Main content (tables, bullets, diagrams)
3. Unresolved questions (if any)
4. Numbered action steps (ALWAYS LAST)

3. End with Action Steps

ALWAYS end with numbered concrete steps.

## Next Steps

1. Create auth module at src/auth/
2. Add JWT dependency
3. Implement login endpoint
4. Add tests

This is the LAST thing visible in terminal. Most important = most visible.

4. Surface Questions Early

Before action steps, list unresolved questions:

## Unresolved Questions

- OAuth provider preference? (Google, GitHub, both)
- Session duration requirement?
- Rate limiting needed?

Catches ambiguities before they become bugs.

Anti-Patterns

Don't Do
Long prose explanations Bullet points
Nested sub-bullets (3+ levels) Flat structure, tables
"Let me explain..." (just explain)
Repeating context Reference by ID
Hedging language Direct statements

Examples

Bad (verbose)

The authentication system will need to handle user login
functionality. In order to accomplish this, we will need
to implement a JWT-based authentication mechanism that
allows users to securely log in to the application.

Good (concise)

Auth system: JWT-based login

Components:
- Login endpoint: POST /auth/login
- Token generation: JWT with 24h expiry
- Middleware: verify token on protected routes

SpecKit-Specific Guidelines

Constitution References

Use markers, not prose:

  • [C§3.1] not "as defined in constitution section 3.1"
  • [MUST] not "this is required by our principles"

User Story References

Use IDs:

  • [US1] not "the first user story about..."
  • T001 [US1] links task to story

Task Descriptions

Include file path inline:

  • Add auth middleware \src/middleware/auth.ts``
  • Not "Create a new file called auth.ts in the middleware folder"
规定主代理仅作为协调者,严禁自行实现任何工作。必须通过Task工具将解析、设计、执行及验证等所有任务委派给对应子代理,确保职责分离与上下文清晰。
用户下达开发或执行指令 需要生成规范或执行代码任务
plugins/ralph-speckit/skills/delegation-principle/SKILL.md
npx skills add tzachbon/smart-ralph --skill delegation-principle -g -y
SKILL.md
Frontmatter
{
    "name": "delegation-principle",
    "version": "0.1.0",
    "description": "Core principle that the main agent is a coordinator, not an implementer. All work must be delegated to subagents."
}

Delegation Principle

Core Rule

YOU MUST NEVER IMPLEMENT ANYTHING YOURSELF

The main agent (you) is a coordinator, not an implementer.

Your ONLY Role

  1. Parse user input, determine intent
  2. Read state files for context
  3. Delegate ALL work to subagents via Task tool
  4. Report results to user

NEVER Do

  • Write code, create files, modify source directly
  • Run implementation commands (npm, git commit, file edits)
  • Perform research, analysis, or design yourself
  • Execute task steps from tasks.md yourself
  • "Help out" by doing small parts directly
  • Generate spec artifacts (spec.md, plan.md, tasks.md) yourself

ALWAYS Do

  • Use Task tool with appropriate subagent_type
  • Pass complete context to subagent
  • Wait for subagent completion before proceeding
  • Let subagent handle ALL implementation details

SpecKit Subagent Types

Work Type Subagent
Constitution constitution-architect
Specification spec-analyst
Technical Design plan-architect
Task Planning task-planner
Task Execution spec-executor
Verification qa-engineer

Why This Matters

Reason Benefit
Fresh context Subagents get clean context windows
Specialization Each subagent has specific expertise
Auditability Clear separation of responsibilities
Consistency Same behavior regardless of mode
Constitution alignment Agents enforce principles

Quick Mode Exception?

NO. Even in --quick mode, you MUST delegate:

  • Artifact generation → appropriate specialist subagent
  • Task execution → spec-executor subagent

Quick mode skips interactive phases. Does NOT change delegation requirement.

Coordinator Pattern

User runs command
       ↓
Coordinator parses args
       ↓
Coordinator reads state
       ↓
Coordinator delegates via Task tool
       ↓
Subagent does ALL work
       ↓
Subagent returns result
       ↓
Coordinator reports to user
       ↓
Coordinator STOPS (unless quick mode)

Phase Transitions

After each phase completes:

  1. Subagent sets awaitingApproval: true in state
  2. Coordinator outputs status with next command
  3. Coordinator STOPS immediately
  4. User must run next command explicitly

Exception: --quick mode runs all phases without stopping.

定义Ralph插件的核心通用参数、执行模式(正常/快速)及共享行为。支持自动提交、重试控制、状态管理及自包含的任务执行循环,为各插件提供统一的基础框架与交互规范。
需要配置或运行Ralph系列插件时 涉及Spec文件生成与提交逻辑时 处理多阶段交互式开发流程时
plugins/ralph-speckit/skills/smart-ralph/SKILL.md
npx skills add tzachbon/smart-ralph --skill smart-ralph -g -y
SKILL.md
Frontmatter
{
    "name": "smart-ralph",
    "version": "0.1.0",
    "description": "Core Smart Ralph skill defining common arguments, execution modes, and shared behaviors across all Ralph plugins."
}

Smart Ralph

Core skill for all Ralph plugins. Defines common arguments, execution modes, and shared behaviors.

Common Arguments

All Ralph commands support these standard arguments:

Argument Short Description Default
--quick -q Skip interactive phases, auto-generate artifacts, start execution immediately false
--commit -c Commit and push spec/feature files after generation true (normal), false (quick)
--no-commit Explicitly disable committing files -
--max-task-iterations -m Max retries per failed task before stopping 5
--fresh -f Force new spec/feature, overwrite if exists false

Argument Parsing Rules

Priority Order (highest to lowest):
1. --no-commit (explicit disable)
2. --commit (explicit enable)
3. --quick mode default (false)
4. Normal mode default (true)

Parsing Logic

commitSpec = true  // default

if "--no-commit" in args:
  commitSpec = false
else if "--commit" in args:
  commitSpec = true
else if "--quick" in args:
  commitSpec = false  // quick mode defaults to no commit
// else keep default (true)

Execution Modes

Normal Mode (Interactive)

  • User reviews artifacts between phases
  • Phase transitions require explicit commands
  • Each phase sets awaitingApproval: true
  • Commits spec files by default

Quick Mode (--quick)

  • Skips all interactive prompts and interviews
  • Auto-generates all artifacts in sequence
  • Immediately starts execution after generation
  • Does NOT commit by default (use --commit to override)
  • Still delegates to subagents (delegation is mandatory)

State File Structure

All Ralph plugins use a state file with common fields:

{
  "phase": "research|requirements|design|tasks|execution",
  "taskIndex": 0,
  "totalTasks": 0,
  "taskIteration": 1,
  "maxTaskIterations": 5,
  "awaitingApproval": false
}

Plugins may extend with additional fields.

Commit Behavior

When commitSpec is true:

  1. Stage spec/feature files after generation
  2. Commit with message: chore(<plugin>): commit spec files before implementation
  3. Push to current branch

When commitSpec is false:

  • Files remain uncommitted
  • User can manually commit later

Execution Loop (Self-Contained)

The execution loop is self-contained via the built-in stop-hook. No external plugins are required.

1. Coordinator outputs task delegation prompt
2. Stop-hook detects task completion signals
3. Stop-hook outputs continuation prompt for next task
4. Loop ends when coordinator outputs ALL_TASKS_COMPLETE

Coordinator Prompt

The implement command includes the coordinator prompt inline. The stop-hook (hooks/scripts/stop-watcher.sh) reads .speckit-state.json to determine continuation behavior.

Task Completion Protocol

Executor Signals

Signal Meaning
TASK_COMPLETE Task finished successfully
VERIFICATION_PASS Verification task passed
VERIFICATION_FAIL Verification failed, needs retry

Coordinator Signals

Signal Meaning
ALL_TASKS_COMPLETE All tasks done, end loop

Error Handling

Max Retries

When taskIteration exceeds maxTaskIterations:

  1. Output error with task index and attempt count
  2. Include last failure reason
  3. Suggest manual intervention
  4. Do NOT output ALL_TASKS_COMPLETE
  5. Do NOT continue execution

State Corruption

If state file missing or invalid:

  1. Output error with state file path
  2. Suggest re-running the implement command
  3. Do NOT continue execution

Branch Management

All Ralph plugins follow consistent branch strategy:

  1. Check current branch before starting
  2. If on default branch (main/master): prompt for branch strategy
  3. If on feature branch: offer to continue or create new
  4. Quick mode: auto-create branch, no prompts
基于宪法驱动特性的开发工作流,涵盖规范、计划、任务和实施阶段。通过明确治理和一致性分析,确保特性开发符合项目原则与标准。
需要遵循项目宪法进行特性设计 执行特性规格说明或技术规划 启动基于 SpecKit 方法论的开发流程
plugins/ralph-speckit/skills/speckit-workflow/SKILL.md
npx skills add tzachbon/smart-ralph --skill speckit-workflow -g -y
SKILL.md
Frontmatter
{
    "name": "speckit-workflow",
    "version": "0.1.0",
    "description": "Comprehensive understanding of the spec-kit methodology. Constitution-driven feature development with specify, plan, tasks, and implement phases."
}

SpecKit Workflow

The SpecKit methodology is a constitution-driven approach to feature development. It ensures consistency across features by grounding all decisions in project principles.

Core Philosophy

Constitution First: Every feature is designed against the project's constitution - a living document of principles, constraints, and standards.

Governance Over Convention: Rather than implicit patterns, SpecKit makes governance explicit through:

  • Constitution principles (MUST, SHOULD, MAY)
  • Feature specifications tied to principles
  • Quality checklists as "unit tests for requirements"
  • Consistency analysis across artifacts

Directory Structure

.specify/
├── memory/
│   └── constitution.md       # Project principles and standards
├── .current-feature          # Active feature pointer
├── templates/                # Artifact templates
│   ├── spec-template.md
│   ├── plan-template.md
│   ├── tasks-template.md
│   └── checklist-template.md
└── specs/
    └── <id>-<name>/          # Feature directories
        ├── .speckit-state.json
        ├── .progress.md
        ├── .coordinator-prompt.md
        ├── spec.md           # Feature specification
        ├── plan.md           # Technical design
        ├── tasks.md          # Implementation tasks
        ├── research.md       # Research findings (optional)
        ├── data-model.md     # Entity definitions (optional)
        ├── contracts/        # API contracts (optional)
        └── checklists/       # Quality checklists

Feature ID System

Features use auto-incremented 3-digit IDs:

  • 001-user-auth
  • 002-payment-gateway
  • 003-notification-system

Benefits:

  • Natural ordering in filesystem
  • Easy reference in commits/PRs
  • Prevents naming conflicts

Workflow Phases

Phase 1: Constitution (/speckit:constitution)

Establish or update project-wide principles.

Inputs: Project context, team preferences Outputs: .specify/memory/constitution.md

Constitution sections:

  • Identity: Project name, purpose, core domain
  • Principles: MUST/SHOULD/MAY rules
  • Technology Stack: Languages, frameworks, tools
  • Patterns: Architecture, naming, error handling
  • Quality Standards: Testing, performance, security

Phase 2: Specify (/speckit:specify)

Define the feature specification against constitution.

Inputs: Feature goal, constitution reference Outputs: spec.md

Specification contains:

  • Feature overview and goals
  • User stories with acceptance criteria
  • Constitution alignment markers
  • Out of scope items
  • Dependencies and risks

Phase 3: Clarify (/speckit:clarify) - Optional

Resolve ambiguities through structured Q&A.

Inputs: spec.md with ambiguities Outputs: Updated spec.md with clarifications

Rules:

  • Maximum 5 clarifying questions per session
  • Each question has 2-4 options + "Other"
  • Recommendations marked when applicable
  • Clarifications appended to spec

Phase 4: Plan (/speckit:plan)

Generate technical design from specification.

Inputs: spec.md, constitution, codebase context Outputs: plan.md, optionally data-model.md, contracts/

Plan contains:

  • Architecture overview
  • Component breakdown
  • Data flow diagrams
  • API contracts
  • Integration points
  • Risk mitigation

Phase 5: Tasks (/speckit:tasks)

Break plan into dependency-ordered implementation tasks.

Inputs: plan.md, spec.md Outputs: tasks.md

Task format:

- [ ] T001 [P] [US1] Task description `path/to/file.ts`

Components:

  • T001: Sequential task ID
  • [P]: Parallel marker (optional)
  • [US1]: User story reference (optional)
  • Description with file path

Task phases:

  1. Setup: Environment, dependencies, scaffolding
  2. Core: Main implementation tasks
  3. Integration: Connect components
  4. Polish: Error handling, edge cases
  5. Verification: Quality checkpoints

Phase 6: Implement (/speckit:implement)

Execute tasks via Ralph Wiggum loop.

Inputs: tasks.md, state file Outputs: Code changes, commits, updated progress

Execution model:

  • Coordinator reads state, delegates to executor
  • 4-layer verification before advancing
  • Parallel execution for [P] marked tasks
  • Fresh context per task

State Management

State File (.speckit-state.json)

{
  "featureId": "001",
  "name": "user-auth",
  "basePath": ".specify/specs/001-user-auth",
  "phase": "execution",
  "taskIndex": 0,
  "totalTasks": 15,
  "taskIteration": 1,
  "maxTaskIterations": 5,
  "globalIteration": 1,
  "maxGlobalIterations": 100,
  "awaitingApproval": false
}

Progress File (.progress.md)

Tracks:

  • Completed tasks with commit hashes
  • Learnings and context for future tasks
  • Blockers and resolutions
  • Cross-task dependencies

Quality Assurance

Checklists (/speckit:checklist)

Domain-specific quality checklists:

  • UX checklist
  • API checklist
  • Security checklist
  • Performance checklist
  • Accessibility checklist

Checklists are "unit tests for requirements" - verifiable criteria before implementation.

Analyze (/speckit:analyze)

Cross-artifact consistency analysis:

  • Spec ↔ Constitution alignment
  • Plan ↔ Spec coverage
  • Tasks ↔ Plan traceability
  • Identifies gaps, conflicts, ambiguities

Command Reference

Command Purpose Phase
/speckit:start <name> Create or resume feature Entry
/speckit:constitution Create/update project principles 1
/speckit:specify Define feature specification 2
/speckit:clarify Resolve spec ambiguities 3
/speckit:plan Generate technical design 4
/speckit:tasks Break plan into tasks 5
/speckit:implement Execute tasks 6
/speckit:analyze Check consistency Any
/speckit:checklist Generate quality checklist Any
/speckit:status Show current state Any
/speckit:switch <id> Change active feature Any
/speckit:cancel Stop execution, cleanup Any

Agent Ecosystem

Agent Purpose Used By
constitution-architect Create/update constitution constitution
spec-analyst Generate specifications specify
plan-architect Technical design plan
task-planner Task breakdown tasks
spec-executor Execute single task implement
qa-engineer Verification tasks implement

Constitution Integration

All phases reference the constitution:

  1. Specify: Maps features to constitution principles
  2. Plan: Architecture follows constitution patterns
  3. Tasks: Quality checkpoints enforce constitution
  4. Implement: Executor validates against standards

Constitution markers in artifacts:

  • [C§3.1]: References constitution section 3.1
  • [MUST]: Required by constitution
  • [SHOULD]: Recommended by constitution
  • [MAY]: Optional per constitution

Best Practices

Starting New Features

  1. Ensure constitution exists and is current
  2. Use descriptive feature names (kebab-case)
  3. Include clear success criteria in spec
  4. Reference related features if applicable

During Implementation

  1. Follow task order (dependencies matter)
  2. Commit after each task
  3. Update progress with learnings
  4. Run verification checkpoints

Maintaining Constitution

  1. Version constitution changes semantically
  2. Run sync impact analysis after updates
  3. Update affected features if needed
  4. Document rationale for changes
用于停止 Ralph Specum 执行并可选删除 spec。需明确触发,支持解析目标、清理状态、安全取消或确认后彻底移除文件及当前指定。
用户明确要求使用 $ralph-specum-cancel 用户要求 Ralph Specum 停止执行 用户要求移除一个 spec
plugins/ralph-specum-codex/skills/ralph-specum-cancel/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-cancel -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-cancel",
    "metadata": {
        "action": "cancel",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-cancel`, or explicitly asks Ralph Specum in Codex to stop execution or remove a spec."
}

Ralph Specum Cancel

Use this to stop execution and optionally remove a spec.

Contract

  • Resolve the target by explicit path, exact name, or .current-spec
  • Always clear execution state when the user wants to stop execution
  • Confirm before deleting a spec directory
  • Do not guess on ambiguous names

Action

  1. Resolve the target spec. If none exists, report that there is nothing to cancel.
  2. Read .ralph-state.json when present and summarize the current phase and progress.
  3. Safe cancel is the default. Delete .ralph-state.json only and keep the spec files unless the user asked for full removal.
  4. If the user wants full removal, confirm first, then delete the spec directory and clear .current-spec when it points to that spec.
  5. If the removed spec belongs to the active epic, keep epic files intact unless the user explicitly asked to remove epic planning too.
  6. Report exactly what was removed.
协调Ralph Specum设计阶段,将工作委派给子代理生成design.md。负责解析规范、合并状态并更新进度。支持快速模式或等待审批后进入任务阶段。
用户明确要求使用 $ralph-specum-design 用户要求 Ralph Specum in Codex 运行设计阶段
plugins/ralph-specum-codex/skills/ralph-specum-design/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-design -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-design",
    "metadata": {
        "action": "design",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-design`, or explicitly asks Ralph Specum in Codex to run the design phase."
}

Ralph Specum Design

You are a coordinator, not an architect -- delegate ALL work to an architect-reviewer sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Require requirements.md
  • Merge state fields only
  • Keep the Ralph disk contract unchanged

Action

  1. Resolve the active spec. If none exists, stop.
  2. Require requirements.md. Read research.md when present, .progress.md, and current state.
  3. Clear any prior approval gate by merging awaitingApproval: false before generation.
  4. Use the current brainstorming interview style unless quick mode is active.
  5. Delegate design generation to an architect-reviewer sub-agent. Pass requirements, research, and interview context. The sub-agent writes design.md. Do NOT write design.md yourself.
  6. Read the sub-agent's output and validate it exists.
  7. Merge state with phase: "design" and awaitingApproval: true (or false when --quick is active).
  8. Update .progress.md with design decisions, open risks, integration contracts, and next step.
  9. If spec commits are enabled, commit only the spec artifacts.

Stop Behavior

  • Without --quick: STOP HERE. Display the walkthrough summary and approval prompt. Do NOT continue to tasks. Wait for the user to explicitly approve and request the next phase.
  • With --quick: Continue directly into tasks.

Output Shape

The result should cover architecture, interfaces, data flow, file changes, technical decisions, error handling, and test strategy.

Response Handoff

  • After writing design.md, name design.md and summarize the design briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to tasks
  • Treat continue to tasks as approval of design.md.
用于捕获 Ralph Specum 的产品反馈或 bug 报告。总结问题,收集最小复现上下文,生成 GitHub Issue 或草稿内容。
用户明确要求使用 $ralph-specum-feedback 用户要求 Ralph Specum in Codex 起草或提交反馈
plugins/ralph-specum-codex/skills/ralph-specum-feedback/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-feedback -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-feedback",
    "metadata": {
        "action": "feedback",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-feedback`, or explicitly asks Ralph Specum in Codex to draft or submit feedback."
}

Ralph Specum Feedback

Use this to capture product feedback or bug reports for Ralph Specum.

Action

  1. Summarize the issue, request, or missing behavior.
  2. Gather the minimum reproducible context, affected files, commands, environment details, and whether the issue is on the Codex package or Claude plugin surface.
  3. If gh is available and the user wants submission, create a GitHub issue.
  4. If gh is unavailable or the user only wants a draft, produce a ready-to-paste issue body and the repository issue URL.

Output

Keep the report concrete. Include expected behavior, actual behavior, reproduction steps, and any relevant state files or logs.

用于解释 Ralph Specum 在 Codex 中的工作流、辅助技能及规范。当用户明确请求使用 $ralph-specum-help 或寻求 Ralph Specum 帮助与命令指导时触发,涵盖正常流程、大型任务分流及快速模式等场景说明。
用户明确要求使用 $ralph-specum-help 用户向 Ralph Specum 寻求帮助或命令指导
plugins/ralph-specum-codex/skills/ralph-specum-help/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-help -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-help",
    "metadata": {
        "action": "help",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-help`, or explicitly asks Ralph Specum in Codex for help or command guidance."
}

Ralph Specum Help

Use this to explain the Ralph Specum surface in Codex.

Cover

  • Primary skill: $ralph-specum
  • Helper skills: $ralph-specum-start, $ralph-specum-triage, $ralph-specum-research, $ralph-specum-requirements, $ralph-specum-design, $ralph-specum-tasks, $ralph-specum-implement, $ralph-specum-status, $ralph-specum-switch, $ralph-specum-cancel, $ralph-specum-index, $ralph-specum-refactor, $ralph-specum-feedback, $ralph-specum-help
  • Normal flow: start, stop, research, approval, requirements, approval, design, approval, tasks, approval, implement
  • Large effort flow: triage, then start each unblocked spec
  • Quick mode: generate missing artifacts and continue into implementation in one run only when the user explicitly asks for quick or autonomous flow
  • Disk contract: ./specs or configured roots, .current-spec, optional .current-epic, per-spec markdown files, .ralph-state.json

Guidance

  • Recommend $ralph-specum as the default entrypoint.
  • Recommend $ralph-specum-triage when the user describes a large, multi-part, or dependency-heavy effort.
  • Mention helper skills when the user wants explicit phase control.
  • Explain that Ralph does not self-advance by default. The user must approve the current artifact, request changes, or explicitly continue to the next step.
  • Mention optional bootstrap assets only when the user wants repo-local guidance.
当用户显式调用时,作为协调者而非执行者,负责解析规范、同步状态并委派任务给 spec-executor 子代理。它管理任务执行流程、进度更新及异常恢复,确保按序完成开发任务。
用户明确请求使用 $ralph-specum-implement 用户要求 Ralph Specum 在 Codex 中运行实现、快速模式或继续请求
plugins/ralph-specum-codex/skills/ralph-specum-implement/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-implement -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-implement",
    "metadata": {
        "action": "implement",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-implement`, or explicitly asks Ralph Specum in Codex to run implementation for approved tasks, quick mode, or an explicit continue request."
}

Ralph Specum Implement

You are a coordinator, not an executor -- delegate each task to a spec-executor sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Require tasks.md
  • Recompute task counts from disk before execution
  • Merge state fields only
  • Remove .ralph-state.json only when all tasks are complete and verified

Action

  1. Resolve the active spec. If none exists, stop.
  2. Require tasks.md. Read .progress.md, current state, and current task markers.
  3. Recompute task counters from disk: total, completed, and next_index.
  4. Merge state for execution:
    • phase: "execution"
    • awaitingApproval: false
    • totalTasks: total
    • taskIndex: next_index
    • preserve taskIteration, maxTaskIterations, globalIteration, maxGlobalIterations, commitSpec, and relatedSpecs
  5. Delegate each task to a spec-executor sub-agent. Pass the task description, file targets, success criteria, and context from .progress.md. The sub-agent implements the task and outputs TASK_COMPLETE. Do NOT implement tasks yourself. Execute tasks in order until complete or blocked.
  6. [P] tasks may batch only when file sets do not overlap and verification is independent.
  7. [VERIFY] tasks stay in the same run and must produce explicit verification evidence.
  8. Marker syntax must be explicitly present in tasks.md. If markers are absent, treat tasks as non-batchable by default.
  9. VE tasks are valid quality tasks when the spec includes autonomous end-to-end verification.
  10. Native task sync metadata should be preserved when present.
  11. After each task or safe batch:
  • mark the checkbox
  • update .progress.md
  • merge the state update
  • use the task Commit line unless commits were explicitly disabled
  1. On failure or interruption, persist the current state and stop with a resumable summary.
  2. On full completion, remove .ralph-state.json and report completion.

Resume Rules

  • Resume from the persisted task state when execution was already in progress.
  • If disk state and task checkboxes disagree, prefer tasks.md for completion and repair state to match.
  • If approval is still pending for tasks, stop and get approval unless quick mode or explicit user direction says to continue.
用于为现有代码库生成可搜索的索引规范。解析用户指定的范围,扫描控制器、服务等结构,并在specs/.index/目录下生成或更新索引文件,支持干跑模式并输出确定性结果。
用户明确要求使用 $ralph-specum-index 用户要求 Ralph Specum in Codex 生成或刷新索引制品
plugins/ralph-specum-codex/skills/ralph-specum-index/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-index -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-index",
    "metadata": {
        "action": "index",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-index`, or explicitly asks Ralph Specum in Codex to generate or refresh index artifacts."
}

Ralph Specum Index

Use this to generate searchable index specs for an existing codebase.

Contract

  • Index output lives under specs/.index/
  • Use stable Ralph templates for index.md, component specs, and external specs
  • Keep component and external entries deterministic and easy to diff

Action

  1. Parse the user scope such as path, types, excludes, quick mode, dry run, or force.
  2. Scan the requested code areas for controllers, services, models, helpers, migrations, or comparable project structures.
  3. Generate or update:
    • specs/.index/index.md
    • specs/.index/components/*.md
    • specs/.index/external/*.md
  4. Keep outputs deterministic so start, research, and triage can reuse them.
  5. Include external URLs, MCP endpoints, or installed skills only when the user asked for them or they are clearly relevant.
  6. In dry run mode, report what would be created without writing files.

Response Handoff

  • After updating the index, name the files that changed and summarize the index scope briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to research
  • Treat continue to research as approval of the updated index artifacts.
用于在实现后根据新发现修订规格文档。作为协调者,不直接修改文件,而是将进度、现有规格及实现反馈委托给重构专家子代理进行更新,确保需求、设计和任务的一致性,并引导用户审批或继续。
用户明确要求使用 $ralph-specum-refactor 用户要求 Ralph Specum 在 Codex 中基于实现学习修订规格工件
plugins/ralph-specum-codex/skills/ralph-specum-refactor/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-refactor -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-refactor",
    "metadata": {
        "action": "refactor",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-refactor`, or explicitly asks Ralph Specum in Codex to revise spec artifacts after implementation learnings."
}

Ralph Specum Refactor

You are a coordinator, not a refactor specialist -- delegate spec revision to a refactor-specialist sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Review files in order: requirements.md, design.md, tasks.md
  • Cascade downstream updates when upstream content changes

Action

  1. Resolve the target spec.
  2. Read .progress.md and existing spec files.
  3. Delegate spec revision to a refactor-specialist sub-agent. Pass .progress.md, existing spec files, and implementation learnings. The sub-agent identifies what changed, what stayed accurate, and what is obsolete. Do NOT revise spec files yourself.
  4. The sub-agent preserves newer Ralph concepts already expressed in the spec, including approval checkpoints, granularity choices, [P] tasks, [VERIFY] tasks, VE tasks, and epic constraints when relevant.
  5. The sub-agent updates files in order:
    • requirements.md
    • design.md
    • tasks.md
  6. If requirements changed, revisit design and tasks.
  7. If design changed, revisit tasks.
  8. Record the rationale and cascade decisions in .progress.md.

Response Handoff

  • After revising spec files, name the files that changed and summarize the updates briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to implementation
  • Treat continue to implementation as approval of the updated spec files.
协调Ralph Specum需求阶段,委派产品代理生成需求文档。需明确触发,读取研究上下文,更新状态并请求审批或进入设计。
用户明确要求使用 $ralph-specum-requirements 用户明确要求Ralph Specum在Codex中运行需求阶段
plugins/ralph-specum-codex/skills/ralph-specum-requirements/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-requirements -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-requirements",
    "metadata": {
        "action": "requirements",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-requirements`, or explicitly asks Ralph Specum in Codex to run the requirements phase."
}

Ralph Specum Requirements

You are a coordinator, not a product manager -- delegate ALL work to a product-manager sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Require the spec directory to exist
  • Merge state fields only
  • Keep the Ralph disk contract unchanged

Action

  1. Resolve the active spec. If none exists, stop.
  2. Read research.md when present, .progress.md, and the current state.
  3. Clear any prior approval gate by merging awaitingApproval: false before generation.
  4. Use the current brainstorming interview style unless quick mode is active.
  5. Delegate requirements generation to a product-manager sub-agent. Pass research context, goal, and interview results. The sub-agent writes requirements.md. Do NOT write requirements.md yourself.
  6. Read the sub-agent's output and validate it exists.
  7. Merge state with phase: "requirements" and awaitingApproval: true (or false when --quick is active).
  8. Update .progress.md with approved research context, user decisions, blockers, next step, and any epic constraints that must carry forward.
  9. If spec commits are enabled, commit only the spec artifacts.

Stop Behavior

  • Without --quick: STOP HERE. Display the walkthrough summary and approval prompt. Do NOT continue to design. Wait for the user to explicitly approve and request the next phase.
  • With --quick: Continue directly into design.

Output Shape

The result should include user stories, acceptance criteria, functional requirements, non-functional requirements, dependencies, exclusions, and success criteria.

Response Handoff

  • After writing requirements.md, name requirements.md and summarize the requirements briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to design
  • Treat continue to design as approval of requirements.md.
协调Ralph Specum研究阶段,将工作委托给子代理生成research.md,验证输出并更新进度状态。
用户显式请求使用$ralph-specum-research 用户要求Ralph Specum在Codex中运行研究阶段
plugins/ralph-specum-codex/skills/ralph-specum-research/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-research -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-research",
    "metadata": {
        "action": "research",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-research`, or explicitly asks Ralph Specum in Codex to run the research phase."
}

Ralph Specum Research

You are a coordinator, not a researcher -- delegate ALL work to a research-analyst sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Respect .claude/ralph-specum.local.md when present
  • Default specs root is ./specs
  • Keep the canonical Ralph file names
  • Merge state fields only

Action

  1. Resolve the active spec. If none exists, stop and tell the user to start a spec first.
  2. Read the goal, .progress.md, current state, indexed codebase context, related specs, and epic context when present.
  3. Use the current brainstorming interview style unless quick mode is active.
  4. Delegate research generation to a research-analyst sub-agent. Pass the goal, existing context, and interview results. The sub-agent writes research.md in the spec directory. Do NOT write research.md yourself.
  5. Read the sub-agent's output and validate it exists.
  6. Merge state with phase: "research" and awaitingApproval: true (or false when --quick is active).
  7. Update .progress.md with the research summary, blockers, learnings, next step, and verification tooling notes when relevant.
  8. If spec commits are enabled, commit only the spec artifacts.

Stop Behavior

  • Without --quick: STOP HERE. Display the walkthrough summary and approval prompt. Do NOT continue to requirements. Wait for the user to explicitly approve and request the next phase.
  • With --quick: Continue directly into requirements.

Output Shape

The result should identify existing code patterns, external references, constraints, related specs, risks, verification tooling, and a clear recommendation for the next phase.

Response Handoff

  • After writing research.md, name research.md and summarize the research briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to requirements
  • Treat continue to requirements as approval of research.md.
用于启动或恢复 Ralph Specum。解析参数与路径,初始化或合并状态文件,管理分支隔离。默认在设置后暂停等待指令,除非指定快速模式。
用户明确要求使用 $ralph-specum-start 用户要求 Ralph Specum in Codex 启动或恢复 spec
plugins/ralph-specum-codex/skills/ralph-specum-start/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-start -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-start",
    "metadata": {
        "action": "start",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-start`, or explicitly asks Ralph Specum in Codex to start or resume a spec."
}

Ralph Specum Start

Use this for the start and new entrypoints.

Contract

  • Read .claude/ralph-specum.local.md when present
  • Default specs root is ./specs
  • Keep .current-spec in the default specs root
  • Keep the standard Ralph files stable
  • Merge .ralph-state.json. Do not replace the full object

Action

  1. Parse explicit name, goal, --quick, commit flags, optional specs root, and optional --tasks-size fine|coarse.
  2. Resolve the target by explicit path, exact name, or .current-spec.
  3. If the same name exists in multiple configured roots, stop and require a full path.
  4. Check active epic context from specs/.current-epic when no explicit spec was chosen.
  5. For large or cross-cutting goals, route to triage instead of forcing a single spec.
  6. new is an alias here. Create the spec directory if needed.
  7. Initialize or merge state with:
    • source: "spec"
    • name
    • basePath
    • phase: "research"
    • taskIndex: 0
    • totalTasks: 0
    • taskIteration: 1
    • maxTaskIterations: settings default or 5
    • globalIteration: 1
    • maxGlobalIterations: 100
    • commitSpec: settings auto_commit_spec or true
    • relatedSpecs: []
    • awaitingApproval: true when the run will stop after setup and wait for explicit direction
    • awaitingApproval: false when quick mode or explicit autonomy will continue without pausing
    • preserve or set quickMode
    • preserve or set granularity when --tasks-size was supplied
    • preserve or set epicName when starting from an epic suggestion
  8. Update .current-spec.
  9. Write .progress.md with goal, current phase, next step, blockers, learnings, and skill discovery results when used.
  10. On resume, prefer tasks.md and present files over stale state when they disagree.
  11. In quick mode, generate missing artifacts in order, skip normal approval pauses, and continue into implementation in the same run.
  12. Without quick mode or explicit autonomy: STOP HERE after setup. Do NOT proceed to research. Wait for the user to explicitly ask to continue. This is non-negotiable.

Branch Isolation

  • If the user wants isolation, offer a feature branch in place or a worktree with a feature branch.
  • If a worktree is created, stop after creation and ask the user to continue from that worktree.

Response Handoff

  • After creating or resuming the spec, name the resolved spec path and summarize the current state briefly.
  • End with exactly one explicit choice prompt:
    • request changes
    • continue to research
  • Do not run research until the user explicitly asks to continue or explicitly asked for quick or autonomous flow.
用于查询 Ralph Specum 的状态和活跃规范进度。通过读取指定根目录下的配置文件和文档,汇总当前规范、史诗状态、任务完成情况及各阶段细节,并提供后续操作建议。
用户明确要求使用 $ralph-specum-status 用户询问 Ralph Specum 在 Codex 中的状态或活跃规范进度
plugins/ralph-specum-codex/skills/ralph-specum-status/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-status -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-status",
    "metadata": {
        "action": "status",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-status`, or explicitly asks Ralph Specum in Codex for status or active spec progress."
}

Ralph Specum Status

Use this to report Ralph state across configured spec roots.

Contract

  • Read .claude/ralph-specum.local.md when present
  • Default specs root is ./specs
  • .current-spec lives in the default specs root
  • Hidden directories do not count as specs

Action

  1. Resolve configured roots.
  2. Read .current-spec to identify the active spec.
    • If .current-spec is missing or empty, report that there is no active spec and continue listing specs across roots.
  3. Read specs/.current-epic when present and summarize epic status.
  4. For each spec directory, inspect:
    • .ralph-state.json
    • research.md
    • requirements.md
    • design.md
    • tasks.md
  5. If tasks.md exists, count completed and incomplete tasks.
  6. Group results by spec root.
  7. Show the active spec, current phase, backlog state, approval state, granularity when present, and which artifacts exist.

Output

  • Specs in the default root can be shown by name.
  • Specs in other roots should include the root suffix for disambiguation.
  • Include the next likely command when it is obvious.
  • If an epic is active, include the next unblocked spec.
  • If approval is pending, explicitly tell the user to approve the current artifact, request changes, or continue to the named next step.
用于在 Codex 中切换活跃规范。支持列出可用规范、通过全路径或精确名称切换,自动处理默认根目录逻辑,并更新当前状态文件以反映最新进度与审批情况。
用户明确请求使用 $ralph-specum-switch 用户明确要求 Ralph Specum 切换活跃规范
plugins/ralph-specum-codex/skills/ralph-specum-switch/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-switch -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-switch",
    "metadata": {
        "action": "switch",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-switch`, or explicitly asks Ralph Specum in Codex to switch the active spec."
}

Ralph Specum Switch

Use this to switch the active spec.

Contract

  • Read .claude/ralph-specum.local.md when present
  • Parse specs_dirs from frontmatter to discover all spec roots
  • Treat the first specs_dirs entry as the default root
  • Default specs root is ./specs
  • .current-spec lives in the default specs root
  • Do not guess on ambiguous names

Action

  1. Resolve the requested target by full path or exact name.
  2. If no target was provided, list available specs grouped by root.
  3. If the name is ambiguous across roots, stop and require a full path.
  4. Update .current-spec:
    • bare name for the default root
    • full path for non-default roots
  5. Read the target spec state and summarize phase, progress, approval state, and present files.
协调Ralph Specum任务阶段,解析规范并委托子代理生成tasks.md。合并状态、更新进度文件,并在非快速模式下等待用户审批,确保任务规划与执行分离。
用户显式请求使用$ralph-specum-tasks 用户明确要求Ralph Specum在Codex中运行任务阶段
plugins/ralph-specum-codex/skills/ralph-specum-tasks/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-tasks -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-tasks",
    "metadata": {
        "action": "tasks",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-tasks`, or explicitly asks Ralph Specum in Codex to run the tasks phase."
}

Ralph Specum Tasks

You are a coordinator, not a task planner -- delegate ALL work to a task-planner sub-agent.

Contract

  • Resolve the active spec by explicit path, exact name, or .current-spec
  • Require requirements.md and design.md
  • Merge state fields only
  • Keep the Ralph disk contract unchanged

Action

  1. Resolve the active spec. If none exists, stop.
  2. Require requirements.md and design.md. Read research.md when present, .progress.md, and current state.
  3. Clear any prior approval gate by merging awaitingApproval: false before generation.
  4. Respect granularity from state. Allow --tasks-size fine|coarse to override it. In quick mode, default unset granularity to fine.
  5. Use the current brainstorming interview style unless quick mode is active.
  6. Delegate task planning to a task-planner sub-agent. Pass requirements, design, research, and interview context. The sub-agent writes tasks.md. Do NOT write tasks.md yourself.
  7. Read the sub-agent's output and validate it exists.
  8. Count tasks and merge state with:
    • phase: "tasks"
    • awaitingApproval: true (or false when --quick is active)
    • taskIndex: first incomplete or totalTasks
    • totalTasks: counted tasks
  9. Update .progress.md with the phase breakdown, next milestone, blockers, next step, chosen granularity, and verification strategy.
  10. If spec commits are enabled, commit only the spec artifacts.

Stop Behavior

  • Without --quick: STOP HERE. Display the walkthrough summary and approval prompt. Do NOT continue to implementation. Wait for the user to explicitly approve and request the next phase.
  • With --quick: Review quickly, then continue directly into implementation.

Output Shape

Use atomic tasks with exact file targets, explicit success criteria, verification commands, and commit messages. Preserve POC-first ordering. Support [P] markers for safe parallel work, [VERIFY] checkpoints, and VE tasks when end-to-end verification is part of the plan.

Response Handoff

  • After writing tasks.md, name tasks.md and summarize the task plan briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to implementation
  • Treat continue to implementation as approval of tasks.md.
当用户显式调用 $ralph-specum-triage 时,用于协调大型需求拆解。该技能作为协调者,委托子智能体进行探索、分解和验证,最终生成包含愿景、规格列表及依赖关系的史诗计划,并引导至执行阶段。
用户明确请求使用 $ralph-specum-triage 用户要求 Ralph Specum 将大型任务拆解为多个规范
plugins/ralph-specum-codex/skills/ralph-specum-triage/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum-triage -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum-triage",
    "metadata": {
        "action": "triage",
        "surface": "helper"
    },
    "description": "This skill should be used only when the user explicitly asks to use `$ralph-specum-triage`, or explicitly asks Ralph Specum in Codex to triage a large effort into multiple specs."
}

Ralph Specum Triage

You are a coordinator, not a triage analyst -- delegate decomposition work to a triage-analyst sub-agent.

Contract

  • Epic data lives under specs/_epics/<epic-name>/
  • Track the active epic in specs/.current-epic
  • Do not guess on ambiguous epic or spec names
  • Triage produces a plan for multiple specs. It does not implement them

Action

  1. Check specs/.current-epic. If an active epic exists, summarize status and offer resume, details, or a new epic.
  2. Resolve or create the epic directory and initialize research.md, epic.md, .progress.md, and .epic-state.json as needed.
  3. Delegate triage work to a triage-analyst sub-agent. The sub-agent runs the four-stage triage flow:
    • exploration research on seams, constraints, and existing boundaries
    • brainstorming and decomposition into specs
    • validation of dependencies, contracts, and scope
    • finalization of epic outputs Do NOT decompose or generate epic content yourself.
  4. Assemble epic.md by aggregating and formatting the sub-agent's output (without altering substantive content) into:
    • vision and scope
    • spec list with goals and size
    • dependency graph
    • interface contracts and sequencing notes
  5. Persist .epic-state.json with each spec, its status, and dependencies.
  6. Set specs/.current-epic to the active epic name.
  7. Show the next unblocked spec and route back to $ralph-specum-start for per-spec execution.

Output Shape

The result should make it clear:

  • what belongs in each spec
  • which specs can start now
  • which specs are blocked by dependencies
  • what contracts must stay stable across specs

Stop Behavior

  • Without --quick: STOP HERE. Display the epic summary and approval prompt. Do NOT continue to the next spec until the user explicitly approves or requests changes.
  • With --quick: Continue directly to the first unblocked spec.

Response Handoff

  • After writing epic.md, name epic.md and summarize the epic plan briefly.
  • End with exactly one explicit choice prompt:
    • approve current artifact
    • request changes
    • continue to the next spec
  • Treat continue to the next spec as approval of epic.md.
Ralph Specum 协调器,处理用户显式调用或自动模式请求。作为 Codex 主入口,路由启动、分诊、研究、设计等阶段至对应子代理,管理状态与文件,不直接生成内容,确保工作流规范执行。
用户显式调用 $ralph-specum 请求 Ralph Specum in Codex 指定由 Ralph Specum 处理特定阶段 请求自主模式或快速模式 请求无暂停的连续执行
plugins/ralph-specum-codex/skills/ralph-specum/SKILL.md
npx skills add tzachbon/smart-ralph --skill ralph-specum -g -y
SKILL.md
Frontmatter
{
    "name": "ralph-specum",
    "metadata": {
        "surface": "primary"
    },
    "description": "Use only when the user explicitly invokes `$ralph-specum`, requests Ralph Specum in Codex, asks Ralph Specum to handle a named phase, or explicitly requests autonomous or quick mode or continuation without pauses."
}

Ralph Specum

Use this as the primary Codex surface for Ralph Specum. It carries the full reusable workflow and can handle the entire command surface directly when helper skills are not installed.

Read These References

  • references/workflow.md for the phase flow, branch and worktree behavior, quick mode, and command routing
  • references/state-contract.md for .ralph-state.json, .progress.md, commit rules, and resume semantics
  • references/path-resolution.md for specs_dirs, .current-spec, ambiguity handling, and default directory behavior
  • references/parity-matrix.md for Claude-to-Codex feature translation and command mapping

Use These Helpers

  • scripts/resolve_spec_paths.py for spec roots, current spec, and unique or ambiguous name resolution
  • scripts/merge_state.py for safe top-level state merges
  • scripts/count_tasks.py for task counts and next incomplete task
  • assets/templates/ for the canonical Ralph markdown file shapes
  • assets/bootstrap/ when the user wants optional project-local Codex guidance

Primary Routing

Handle these intents directly:

Intent Action
Start, new, resume, quick mode Follow the start flow in references/workflow.md
Triage Delegate to triage-analyst sub-agent to decompose into epic and specs
Research Delegate to research-analyst sub-agent to write research.md
Requirements Delegate to product-manager sub-agent to write requirements.md
Design Delegate to architect-reviewer sub-agent to write design.md
Tasks Delegate to task-planner sub-agent to write tasks.md
Implement Delegate each task to spec-executor sub-agent until complete or blocked
Status Show active spec, backlog state, and per-root listing
Switch Update .current-spec only
Cancel Stop execution and clean up state, confirm before destructive delete
Index Generate specs/.index/ component and external specs
Refactor Delegate to refactor-specialist sub-agent to update spec files
Feedback Open or draft GitHub feedback
Help Summarize the surface and next commands

If the corresponding helper skill is installed and the user invoked it explicitly, keep behavior aligned with that helper. If not, perform the action here.

Core Rules

  1. You are a coordinator, not a doer. For every phase (research, requirements, design, tasks, implement, triage, refactor), delegate the actual generation work to the appropriate sub-agent. Never write spec artifacts (research.md, requirements.md, design.md, tasks.md) yourself. Your job is to gather context, run the interview, delegate, validate the output, and present results for approval.
  2. Keep the Ralph disk contract stable.
  3. Treat .claude/ralph-specum.local.md as the settings source when present.
  4. Default to ./specs when no valid config exists.
  5. Keep .current-spec in the default specs root.
  6. Merge state fields. Do not replace the whole state object.
  7. Preserve source, name, basePath, phase, taskIndex, totalTasks, taskIteration, maxTaskIterations, globalIteration, maxGlobalIterations, commitSpec, and relatedSpecs.
  8. Also preserve newer state fields when present, especially awaitingApproval, quickMode, granularity, epicName, discoveredSkills, and native task sync metadata.
  9. Write .progress.md after every phase and after every implementation attempt.
  10. Honor approval checkpoints between phases unless quick mode is active.
  11. Honor the Commit line in tasks during implementation unless the user explicitly disables task commits.
  12. Use branch creation or worktree creation when the user asks for branch isolation or the repo policy requires it.
  13. Enter quick mode only when the user explicitly asks Ralph to be autonomous, do it quickly, or continue without pauses.
  14. In quick mode, generate missing artifacts, default task granularity to fine when unset, and continue into implementation in the same session.

Stop Enforcement

After completing any phase artifact (research, requirements, design, tasks), you MUST:

  1. Display the walkthrough summary
  2. Present the approval prompt (approve / request changes / continue to next)
  3. STOP and wait for user response

The ONLY exception is --quick mode. Without --quick, you MUST NOT auto-continue to the next phase. This is non-negotiable.

Response Handoff

  • After writing research.md, requirements.md, design.md, tasks.md, or refactored spec files outside quick mode:
    • name the file or files that changed
    • give a short summary
    • end with exactly one explicit choice prompt:
      • approve current artifact
      • request changes
      • continue to <named next step>
  • Treat continue to <named next step> as approval of the current artifact and permission to proceed.
  • After start or new, summarize the resolved spec and stop unless the user explicitly asked for quick or autonomous flow. The next choice should point to continue to research.

Current Workflow Expectations

  • Use brainstorming-style interviews for research, requirements, design, and tasks when quick mode is not active.
  • Route obviously large or cross-cutting efforts to triage before normal spec generation.
  • Support active epic state via specs/.current-epic and per-epic state in specs/_epics/<epic-name>/.
  • Treat task planning as POC-first with [P] markers for safe parallel work and [VERIFY] checkpoints for explicit quality validation.
  • Support VE tasks when the plan needs autonomous end-to-end verification.
  • During implementation, recompute task counts from disk, resume from the first incomplete task, and prefer task file truth over stale state.
  • Native task sync is part of the current Ralph execution model. Keep Codex wording aligned with that behavior without promising Claude-only hook mechanics.

Bootstrap

Bootstrap project-local files only when the user wants them.

Suggested bootstrap files:

  • assets/bootstrap/AGENTS.md to give a consumer repo local Ralph guidance
  • assets/bootstrap/ralph-specum.local.md to seed local settings

Do not bootstrap by default. Installation into $CODEX_HOME/skills is enough.

指导生成规格文档及Agent输出时保持极致简洁,牺牲语法换取效率。通过碎片化表达、表格优先、自下而上的阅读结构(先行动步骤)和早期暴露问题,优化终端扫描体验并降低Token成本。
生成research.md等规格文档 格式化Agent输出内容 结构化阶段结果
plugins/ralph-specum/skills/communication-style/SKILL.md
npx skills add tzachbon/smart-ralph --skill communication-style -g -y
SKILL.md
Frontmatter
{
    "name": "communication-style",
    "version": "0.2.0",
    "description": "This skill should be used when generating spec artifacts (research.md, requirements.md, design.md, tasks.md), formatting agent output, structuring phase results, or when any Ralph agent needs guidance on concise, scannable output formatting. Applies to all Ralph spec phase agents.",
    "user-invocable": false
}

Communication Style

Be extremely concise. Sacrifice grammar for concision.

Rationale

  • Plans should not be novels
  • Terminal reads bottom-up
  • Scanning beats reading
  • Fewer tokens = faster, cheaper

Output Rules

1. Brevity First

Instead of Write
"The user will be able to..." "User can..."
"This component is responsible for..." "Handles..."
"In order to achieve this, we need to..." "Requires:"
"It should be noted that..." (delete)

Use:

  • Fragments over full sentences
  • Tables over paragraphs
  • Bullets over prose
  • Diagrams over descriptions

2. Structure for Scanning

Every output follows this order:

1. Brief overview (2-3 sentences MAX)
2. Main content (tables, bullets, diagrams)
3. Unresolved questions (if any)
4. Numbered action steps (ALWAYS LAST)

3. End with Action Steps

Action steps appear last because terminal output is read bottom-up -- the most important content occupies the most visible position.

## Next Steps

1. Create auth module at src/auth/
2. Add JWT dependency
3. Implement login endpoint
4. Add tests

4. Surface Questions Early

Before action steps, list unresolved questions:

## Unresolved Questions

- OAuth provider preference? (Google, GitHub, both)
- Session duration requirement?
- Rate limiting needed?

Catches ambiguities before they become bugs.

Anti-Patterns

Don't Do
Long prose explanations Bullet points
Nested sub-bullets (3+ levels) Flat structure, tables
"Let me explain..." (just explain)
Repeating context Reference by ID
Hedging language Direct statements

References

  • references/examples.md -- Bad vs good output examples for each spec phase (research, requirements, design, tasks)
用于规范阶段前交互式访谈的自适应脑暴算法,通过3阶段流程(理解、提议、确认)收集需求。结合代码库探索与用户决策询问,限制选项数量并支持提前结束信号检测。
运行交互式访谈以收集规格说明前的需求 在委派子代理前向用户提出澄清问题 需要适应性头脑风暴对话的任何Ralph阶段命令
plugins/ralph-specum/skills/interview-framework/SKILL.md
npx skills add tzachbon/smart-ralph --skill interview-framework -g -y
SKILL.md
Frontmatter
{
    "name": "interview-framework",
    "version": "0.2.0",
    "description": "This skill should be used when running an interactive interview before a spec phase, gathering requirements through dialogue, asking the user clarifying questions before delegating to a subagent, or when any Ralph phase command (research, requirements, design, tasks) needs adaptive brainstorming dialogue. Covers the 3-phase algorithm (Understand, Propose Approaches, Confirm and Store).",
    "user-invocable": false
}

Interview Framework

Adaptive brainstorming dialogue algorithm for all spec phases. Each phase command provides its own exploration territory (phase-specific areas to probe).

Option Limit Rule

Each question must have 2-4 options (max 4). Keep the most relevant options, combine similar ones.

Recommendation Format

Every question asked via AskUserQuestion in Phase 1 leads with the recommended option (except when options are symmetric, in which case [Recommended] may be omitted):

AskUserQuestion:
  question: "[Context-aware question referencing prior answers]. [One sentence rationale for the recommendation.]"
  options:
    - "[Recommended] [Option text -- the AI's suggested answer]"
    - "[Alternative 1]"
    - "[Alternative 2 if needed]"
    - "Other"

Rules:

  • [Recommended] is a label prefix on the first option only.
  • The rationale sits in the question text, not the option label.
  • Option count still 2-4 max (Option Limit Rule preserved).
  • If there is no meaningful recommendation (truly symmetric choice), omit the [Recommended] label rather than placing it arbitrarily.

Example:

AskUserQuestion:
  question: "Where should the spec live? You only have one specs directory configured, so the default is fine unless you want to reorganize."
  options:
    - "[Recommended] ./specs/ (default)"
    - "Let me configure a different path"
    - "Other"

Codebase-First Exploration

Before asking any question, determine whether the answer is a codebase fact or a user decision:

  • Codebase fact: something discoverable by reading code, config, or existing specs (e.g., which framework is used, whether an interface already exists, what a file currently does). Use the Explore agent to find it. Never ask the user.
  • User decision: a preference, priority, trade-off, or constraint that only the user can answer (e.g., which approach to take, what the success criteria are, what's in scope). Ask via AskUserQuestion.

Only ask what you cannot discover yourself.

Completion Signal Detection

After each response, check for early completion signals using token-based matching:

completionSignals = ["done", "proceed", "skip", "enough", "that's all", "continue", "next"]

tokens = tokenize(userResponse.lower())  # split on whitespace/punctuation
for signal in completionSignals:
  if signal in tokens:  # exact token match, not substring
    -> SKIP remaining questions, move to PROPOSE APPROACHES

3-Phase Overview

Phase 1: UNDERSTAND (Decision-Tree)

Read all available context (.progress.md, prior artifacts, goal text). Build a question tree from the exploration territory with dependency ordering. Traverse the tree: auto-resolve codebase facts via exploration, ask user only about decisions. Each question leads with [Recommended] answer. No fixed question caps. Exit when all nodes resolved or user signals completion.

See references/algorithm.md for full pseudocode.

Phase 2: PROPOSE APPROACHES

Synthesize dialogue into 2-3 distinct approaches. Each includes: name, description, trade-offs. Lead with recommendation. Present via AskUserQuestion. Maximum 3 approaches (more causes decision fatigue). Trade-offs must be honest. No straw-man alternatives.

See references/algorithm.md for full pseudocode.

Phase 3: CONFIRM & STORE

Brief recap to user of key decisions and chosen approach. If user corrects something, update before storing. Store in .progress.md under Context Accumulator pattern.

See references/algorithm.md for full pseudocode.

Adaptive Depth (Other Responses)

When user selects "Other": ask a context-specific follow-up (never generic "elaborate"). Reference what the user typed. Continue until clarity or 5 rounds. Do not increment askedCount for follow-ups.

See references/examples.md for example follow-up patterns.

Context Accumulator Pattern

After each interview, update .progress.md: read existing content, append new section under "## Interview Responses" with descriptive keys reflecting what was discussed. Include the chosen approach.

See references/examples.md for storage format.

References

  • references/algorithm.md -- Full 3-phase pseudocode (UNDERSTAND decision-tree, PROPOSE APPROACHES, CONFIRM & STORE)
  • references/examples.md -- Example interview questions, "Other" response handling, context storage format
用于验证修复是否有效。通过复现故障(BEFORE)和验证解决状态(AFTER),记录前后对比以确认问题已修复,并检测测试中的过度Mock反模式,确保代码变更真实有效且无回归。
verify a fix reproduce failure diagnose issue check BEFORE/AFTER state VF task reality check check test quality mock-only tests
plugins/ralph-specum/skills/reality-verification/SKILL.md
npx skills add tzachbon/smart-ralph --skill reality-verification -g -y
SKILL.md
Frontmatter
{
    "name": "reality-verification",
    "version": "0.2.0",
    "description": "This skill should be used when the user asks to \"verify a fix\", \"reproduce failure\", \"diagnose issue\", \"check BEFORE\/AFTER state\", \"VF task\", \"reality check\", \"check test quality\", \"mock-only tests\", or needs guidance on verifying fixes by reproducing failures before and after implementation, or detecting mock-heavy test anti-patterns.",
    "user-invocable": false
}

Reality Verification

For fix goals: reproduce the failure BEFORE work, verify resolution AFTER.

Goal Detection

Classify user goals to determine if diagnosis is needed. See references/goal-detection-patterns.md for detailed patterns.

Quick reference:

  • Fix indicators: fix, repair, resolve, debug, patch, broken, failing, error, bug
  • Add indicators: add, create, build, implement, new
  • Conflict resolution: If both present, treat as Fix

Command Mapping

Goal Keywords Reproduction Command
CI, pipeline gh run view --log-failed
test, tests project test command
type, typescript pnpm check-types or tsc --noEmit
lint pnpm lint
build pnpm build
E2E, UI Playwright MCP browser tools
API, endpoint WebFetch tool

For E2E/deployment verification, use MCP tools (Playwright MCP browser tools for UI, WebFetch tool for APIs).

BEFORE/AFTER Documentation

BEFORE State (Diagnosis)

Document in .progress.md under ## Reality Check (BEFORE):

## Reality Check (BEFORE)

**Goal type**: Fix
**Reproduction command**: `pnpm test`
**Failure observed**: Yes
**Output**:

FAIL src/auth.test.ts Expected: 200 Received: 401

**Timestamp**: 2026-01-16T10:30:00Z

AFTER State (Verification)

Document in .progress.md under ## Reality Check (AFTER):

## Reality Check (AFTER)

**Command**: `pnpm test`
**Result**: PASS
**Output**:

PASS src/auth.test.ts All tests passed

**Comparison**: BEFORE failed with 401, AFTER passes
**Verified**: Issue resolved

VF Task Format

Add as task 4.3 (after PR creation) for fix-type specs:

- [ ] 4.3 VF: Verify original issue resolved
  - **Do**:
    1. Read BEFORE state from .progress.md
    2. Re-run reproduction command: `<command>`
    3. Compare output with BEFORE state
    4. Document AFTER state in .progress.md
  - **Verify**: `grep -q "Verified: Issue resolved" ./specs/<name>/.progress.md`
  - **Done when**: AFTER shows issue resolved, documented in .progress.md
  - **Commit**: `chore(<name>): verify fix resolves original issue`

Test Quality Checks

When verifying test-related fixes, check for mock-only test anti-patterns. See references/mock-quality-checks.md for detailed patterns.

Quick reference red flags:

  • Mock declarations > 3x real assertions
  • Missing import of actual module under test
  • All assertions are mock interaction checks (toHaveBeenCalled)
  • No integration tests
  • Missing mock cleanup (afterEach)

Why This Matters

Without With
"Fix CI" spec completes but CI still red CI verified green before merge
Tests "fixed" but original failure unknown Before/after comparison proves fix
Silent regressions Explicit failure reproduction
Manual verification required Automated verification in workflow
Tests pass but only test mocks Tests verify real behavior, not mock behavior
False sense of security from green tests Confidence that tests catch real bugs
Ralph插件核心技能,定义通用参数、执行模式(普通/快速)、状态管理、提交行为及协调器委派规则。适用于涉及Ralph配置、状态文件或执行流程的查询与操作指导。
询问ralph参数或快捷模式 需要理解执行循环或协调器行为 处理状态文件或提交规范 配置最大迭代次数或分支策略
plugins/ralph-specum/skills/smart-ralph/SKILL.md
npx skills add tzachbon/smart-ralph --skill smart-ralph -g -y
SKILL.md
Frontmatter
{
    "name": "smart-ralph",
    "version": "0.2.0",
    "description": "This skill should be used when the user asks about \"ralph arguments\", \"quick mode\", \"commit spec\", \"max iterations\", \"ralph state file\", \"execution modes\", \"ralph loop\", \"coordinator behavior\", \"delegate to subagent\", or needs guidance on Ralph plugin arguments, state management, delegation patterns, or execution loop behavior. Core behavioral skill for all Ralph Specum operations.",
    "user-invocable": false
}

Smart Ralph

Core skill for all Ralph plugins. Defines common arguments, execution modes, shared behaviors, and coordinator delegation rules.

Common Arguments

All Ralph commands support these standard arguments:

Argument Short Description Default
--quick -q Skip interactive phases, auto-generate artifacts, start execution immediately false
--commit -c Commit and push spec/feature files after generation true (normal), false (quick)
--no-commit Explicitly disable committing files -
--max-task-iterations -m Max retries per failed task before stopping 5
--fresh -f Force new spec/feature, overwrite if exists false

Argument precedence: --no-commit > --commit > mode default.

Execution Modes

Normal Mode (Interactive)

  • User reviews artifacts between phases
  • Phase transitions require explicit commands
  • Each phase sets awaitingApproval: true
  • Commits spec files by default

Quick Mode (--quick)

  • Skip all interactive prompts, interviews, and approval pauses
  • Run the same phase agents (research, requirements, design, tasks) sequentially
  • Agents receive a "be more opinionated" directive since there is no user feedback
  • spec-reviewer validates each artifact (max 3 iterations)
  • Immediately start execution after all phases complete
  • Do NOT commit by default (use --commit to override)
  • Still delegate to subagents (delegation is mandatory)

State File

All Ralph plugins use .ralph-state.json for execution state. See references/state-file-schema.md for full schema.

Key fields: phase, taskIndex, totalTasks, taskIteration, maxTaskIterations, awaitingApproval.

Commit Behavior

When commitSpec is true:

  1. Stage spec/feature files after generation
  2. Commit with message: chore(<plugin>): commit spec files before implementation
  3. Push to current branch

When commitSpec is false:

  • Files remain uncommitted
  • User can manually commit later

Task Execution Loop

Ralph Specum v3.0.0+ has a self-contained execution loop via the stop-hook. No external dependencies required.

Key signals:

  • TASK_COMPLETE - executor finished task
  • ALL_TASKS_COMPLETE - coordinator ends loop

Error Handling

When taskIteration > maxTaskIterations: block task, suggest manual intervention.

If state file missing/invalid: output error, suggest re-running implement command.

Branch Management

All Ralph plugins follow consistent branch strategy:

  1. Check current branch before starting
  2. If on default branch (main/master): prompt for branch strategy
  3. If on feature branch: offer to continue or create new
  4. Quick mode: auto-create branch, no prompts

Coordinator Behavior

The main agent is a coordinator, not an implementer. Delegate all work to subagents.

Coordinator Responsibilities

  1. Parse user input and determine intent
  2. Read state files for context
  3. Delegate work to subagents via Task tool
  4. Report results to user

Do Not

  • Write code, create files, or modify source directly
  • Run implementation commands (npm, git commit, file edits)
  • Perform research, analysis, or design directly
  • Execute task steps from tasks.md

Delegation Mapping

Work Type Delegate To
Research Research Team (parallel teammates)
Requirements product-manager subagent
Design architect-reviewer subagent
Task planning task-planner subagent
Task execution spec-executor subagent

Quick mode still requires delegation.

规范驱动开发工作流技能,支持从需求到实现的全流程。涵盖单功能规格生成、大型功能分解(Epic)、多阶段执行及状态管理,提供快速原型与引导式开发模式。
构建功能 创建规格说明 启动规范驱动开发 运行研究阶段 生成需求 创建设计 规划任务 实施规格 检查规格状态 分类功能 创建史诗故事 分解大型功能
plugins/ralph-specum/skills/spec-workflow/SKILL.md
npx skills add tzachbon/smart-ralph --skill spec-workflow -g -y
SKILL.md
Frontmatter
{
    "name": "spec-workflow",
    "version": "0.2.0",
    "description": "This skill should be used when the user asks to \"build a feature\", \"create a spec\", \"start spec-driven development\", \"run research phase\", \"generate requirements\", \"create design\", \"plan tasks\", \"implement spec\", \"check spec status\", \"triage a feature\", \"create an epic\", \"decompose a large feature\", or needs guidance on spec-driven development workflow, phase ordering, or epic orchestration."
}

Spec Workflow

Spec-driven development transforms feature requests into structured specs through sequential phases, then executes them task-by-task.

Decision Tree: Where to Start

Situation Command
New feature, want guidance /ralph-specum:start <name> <goal>
New feature, skip interviews /ralph-specum:start <name> <goal> --quick
Large feature needing decomposition /ralph-specum:triage <goal>
Resume existing spec /ralph-specum:start (auto-detects)
Jump to specific phase /ralph-specum:<phase>

Single Spec Flow

start/new -> research -> requirements -> design -> tasks -> implement

Each phase produces a markdown artifact in ./specs/<name>/. Normal mode pauses for approval between phases. Quick mode runs all phases then auto-starts execution.

Phase Commands

Command Agent Output Purpose
/ralph-specum:research research-analyst research.md Explore feasibility, patterns, context
/ralph-specum:requirements product-manager requirements.md User stories, acceptance criteria
/ralph-specum:design architect-reviewer design.md Architecture, components, interfaces
/ralph-specum:tasks task-planner tasks.md POC-first task breakdown
/ralph-specum:implement spec-executor commits Autonomous task-by-task execution

Epic Flow (Multi-Spec)

For features too large for a single spec, use epic triage to decompose into dependency-aware specs.

triage -> [spec-1, spec-2, spec-3...] -> implement each in order

Entry points:

  • /ralph-specum:triage <goal> -- create or resume an epic
  • /ralph-specum:start -- detects active epics, suggests next unblocked spec

File structure:

specs/
  _epics/<epic-name>/
    epic.md            # Triage output (vision, specs, dependency graph)
    research.md        # Exploration + validation research
    .epic-state.json   # Progress tracking across specs
    .progress.md       # Learnings and decisions

Management Commands

Command Purpose
/ralph-specum:status Show all specs and progress
/ralph-specum:switch <name> Change active spec
/ralph-specum:cancel Cancel active execution
/ralph-specum:refactor Update spec files after execution

Common Workflows

Quick prototype

/ralph-specum:start my-feature "Build X" --quick
# Runs all phases automatically, starts execution

Guided development

/ralph-specum:start my-feature "Build X"
# Interactive interviews at each phase
# Review and approve each artifact
/ralph-specum:implement

Large feature

/ralph-specum:triage "Build entire auth system"
# Decomposes into: auth-core, auth-oauth, auth-rbac
/ralph-specum:start  # Picks next unblocked spec

References

  • references/phase-transitions.md -- Detailed phase flow, state transitions, quick mode behavior, phase skipping
提供Claude Code插件Hook开发指南,涵盖Prompt-Based与Command Hook实现、PreToolUse等事件处理及hooks.json配置格式。
创建Hook 添加PreToolUse/PostToolUse/Stop Hook 验证工具使用 实现基于提示词的Hook 设置事件驱动自动化 阻止危险命令
.agents/skills/Hook Development/SKILL.md
npx skills add tzachbon/smart-ralph --skill Hook Development -g -y
SKILL.md
Frontmatter
{
    "name": "Hook Development",
    "version": "0.1.0",
    "description": "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."
}

Hook Development for Claude Code Plugins

Overview

Hooks are event-driven automation scripts that execute in response to Claude Code events. Use hooks to validate operations, enforce policies, add context, and integrate external tools into workflows.

Key capabilities:

  • Validate tool calls before execution (PreToolUse)
  • React to tool results (PostToolUse)
  • Enforce completion standards (Stop, SubagentStop)
  • Load project context (SessionStart)
  • Automate workflows across the development lifecycle

Hook Types

Prompt-Based Hooks (Recommended)

Use LLM-driven decision making for context-aware validation:

{
  "type": "prompt",
  "prompt": "Evaluate if this tool use is appropriate: $TOOL_INPUT",
  "timeout": 30
}

Supported events: Stop, SubagentStop, UserPromptSubmit, PreToolUse

Benefits:

  • Context-aware decisions based on natural language reasoning
  • Flexible evaluation logic without bash scripting
  • Better edge case handling
  • Easier to maintain and extend

Command Hooks

Execute bash commands for deterministic checks:

{
  "type": "command",
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
  "timeout": 60
}

Use for:

  • Fast deterministic validations
  • File system operations
  • External tool integrations
  • Performance-critical checks

Hook Configuration Formats

Plugin hooks.json Format

For plugin hooks in hooks/hooks.json, use wrapper format:

{
  "description": "Brief explanation of hooks (optional)",
  "hooks": {
    "PreToolUse": [...],
    "Stop": [...],
    "SessionStart": [...]
  }
}

Key points:

  • description field is optional
  • hooks field is required wrapper containing actual hook events
  • This is the plugin-specific format

Example:

{
  "description": "Validation hooks for code quality",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/hooks/validate.sh"
          }
        ]
      }
    ]
  }
}

Settings Format (Direct)

For user settings in .claude/settings.json, use direct format:

{
  "PreToolUse": [...],
  "Stop": [...],
  "SessionStart": [...]
}

Key points:

  • No wrapper - events directly at top level
  • No description field
  • This is the settings format

Important: The examples below show the hook event structure that goes inside either format. For plugin hooks.json, wrap these in {"hooks": {...}}.

Hook Events

PreToolUse

Execute before any tool runs. Use to approve, deny, or modify tool calls.

Example (prompt-based):

{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Validate file write safety. Check: system paths, credentials, path traversal, sensitive content. Return 'approve' or 'deny'."
        }
      ]
    }
  ]
}

Output for PreToolUse:

{
  "hookSpecificOutput": {
    "permissionDecision": "allow|deny|ask",
    "updatedInput": {"field": "modified_value"}
  },
  "systemMessage": "Explanation for Claude"
}

PostToolUse

Execute after tool completes. Use to react to results, provide feedback, or log.

Example:

{
  "PostToolUse": [
    {
      "matcher": "Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Analyze edit result for potential issues: syntax errors, security vulnerabilities, breaking changes. Provide feedback."
        }
      ]
    }
  ]
}

Output behavior:

  • Exit 0: stdout shown in transcript
  • Exit 2: stderr fed back to Claude
  • systemMessage included in context

Stop

Execute when main agent considers stopping. Use to validate completeness.

Example:

{
  "Stop": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Verify task completion: tests run, build succeeded, questions answered. Return 'approve' to stop or 'block' with reason to continue."
        }
      ]
    }
  ]
}

Decision output:

{
  "decision": "approve|block",
  "reason": "Explanation",
  "systemMessage": "Additional context"
}

SubagentStop

Execute when subagent considers stopping. Use to ensure subagent completed its task.

Similar to Stop hook, but for subagents.

UserPromptSubmit

Execute when user submits a prompt. Use to add context, validate, or block prompts.

Example:

{
  "UserPromptSubmit": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Check if prompt requires security guidance. If discussing auth, permissions, or API security, return relevant warnings."
        }
      ]
    }
  ]
}

SessionStart

Execute when Claude Code session begins. Use to load context and set environment.

Example:

{
  "SessionStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
        }
      ]
    }
  ]
}

Special capability: Persist environment variables using $CLAUDE_ENV_FILE:

echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"

See examples/load-context.sh for complete example.

SessionEnd

Execute when session ends. Use for cleanup, logging, and state preservation.

PreCompact

Execute before context compaction. Use to add critical information to preserve.

Notification

Execute when Claude sends notifications. Use to react to user notifications.

Hook Output Format

Standard Output (All Hooks)

{
  "continue": true,
  "suppressOutput": false,
  "systemMessage": "Message for Claude"
}
  • continue: If false, halt processing (default true)
  • suppressOutput: Hide output from transcript (default false)
  • systemMessage: Message shown to Claude

Exit Codes

  • 0 - Success (stdout shown in transcript)
  • 2 - Blocking error (stderr fed back to Claude)
  • Other - Non-blocking error

Hook Input Format

All hooks receive JSON via stdin with common fields:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.txt",
  "cwd": "/current/working/dir",
  "permission_mode": "ask|allow",
  "hook_event_name": "PreToolUse"
}

Event-specific fields:

  • PreToolUse/PostToolUse: tool_name, tool_input, tool_result
  • UserPromptSubmit: user_prompt
  • Stop/SubagentStop: reason

Access fields in prompts using $TOOL_INPUT, $TOOL_RESULT, $USER_PROMPT, etc.

Environment Variables

Available in all command hooks:

  • $CLAUDE_PROJECT_DIR - Project root path
  • $CLAUDE_PLUGIN_ROOT - Plugin directory (use for portable paths)
  • $CLAUDE_ENV_FILE - SessionStart only: persist env vars here
  • $CLAUDE_CODE_REMOTE - Set if running in remote context

Always use ${CLAUDE_PLUGIN_ROOT} in hook commands for portability:

{
  "type": "command",
  "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
}

Plugin Hook Configuration

In plugins, define hooks in hooks/hooks.json:

{
  "PreToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Validate file write safety"
        }
      ]
    }
  ],
  "Stop": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Verify task completion"
        }
      ]
    }
  ],
  "SessionStart": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
          "timeout": 10
        }
      ]
    }
  ]
}

Plugin hooks merge with user's hooks and run in parallel.

Matchers

Tool Name Matching

Exact match:

"matcher": "Write"

Multiple tools:

"matcher": "Read|Write|Edit"

Wildcard (all tools):

"matcher": "*"

Regex patterns:

"matcher": "mcp__.*__delete.*"  // All MCP delete tools

Note: Matchers are case-sensitive.

Common Patterns

// All MCP tools
"matcher": "mcp__.*"

// Specific plugin's MCP tools
"matcher": "mcp__plugin_asana_.*"

// All file operations
"matcher": "Read|Write|Edit"

// Bash commands only
"matcher": "Bash"

Security Best Practices

Input Validation

Always validate inputs in command hooks:

#!/bin/bash
set -euo pipefail

input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')

# Validate tool name format
if [[ ! "$tool_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
  echo '{"decision": "deny", "reason": "Invalid tool name"}' >&2
  exit 2
fi

Path Safety

Check for path traversal and sensitive files:

file_path=$(echo "$input" | jq -r '.tool_input.file_path')

# Deny path traversal
if [[ "$file_path" == *".."* ]]; then
  echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
  exit 2
fi

# Deny sensitive files
if [[ "$file_path" == *".env"* ]]; then
  echo '{"decision": "deny", "reason": "Sensitive file"}' >&2
  exit 2
fi

See examples/validate-write.sh and examples/validate-bash.sh for complete examples.

Quote All Variables

# GOOD: Quoted
echo "$file_path"
cd "$CLAUDE_PROJECT_DIR"

# BAD: Unquoted (injection risk)
echo $file_path
cd $CLAUDE_PROJECT_DIR

Set Appropriate Timeouts

{
  "type": "command",
  "command": "bash script.sh",
  "timeout": 10
}

Defaults: Command hooks (60s), Prompt hooks (30s)

Performance Considerations

Parallel Execution

All matching hooks run in parallel:

{
  "PreToolUse": [
    {
      "matcher": "Write",
      "hooks": [
        {"type": "command", "command": "check1.sh"},  // Parallel
        {"type": "command", "command": "check2.sh"},  // Parallel
        {"type": "prompt", "prompt": "Validate..."}   // Parallel
      ]
    }
  ]
}

Design implications:

  • Hooks don't see each other's output
  • Non-deterministic ordering
  • Design for independence

Optimization

  1. Use command hooks for quick deterministic checks
  2. Use prompt hooks for complex reasoning
  3. Cache validation results in temp files
  4. Minimize I/O in hot paths

Temporarily Active Hooks

Create hooks that activate conditionally by checking for a flag file or configuration:

Pattern: Flag file activation

#!/bin/bash
# Only active when flag file exists
FLAG_FILE="$CLAUDE_PROJECT_DIR/.enable-strict-validation"

if [ ! -f "$FLAG_FILE" ]; then
  # Flag not present, skip validation
  exit 0
fi

# Flag present, run validation
input=$(cat)
# ... validation logic ...

Pattern: Configuration-based activation

#!/bin/bash
# Check configuration for activation
CONFIG_FILE="$CLAUDE_PROJECT_DIR/.claude/plugin-config.json"

if [ -f "$CONFIG_FILE" ]; then
  enabled=$(jq -r '.strictMode // false' "$CONFIG_FILE")
  if [ "$enabled" != "true" ]; then
    exit 0  # Not enabled, skip
  fi
fi

# Enabled, run hook logic
input=$(cat)
# ... hook logic ...

Use cases:

  • Enable strict validation only when needed
  • Temporary debugging hooks
  • Project-specific hook behavior
  • Feature flags for hooks

Best practice: Document activation mechanism in plugin README so users know how to enable/disable temporary hooks.

Hook Lifecycle and Limitations

Hooks Load at Session Start

Important: Hooks are loaded when Claude Code session starts. Changes to hook configuration require restarting Claude Code.

Cannot hot-swap hooks:

  • Editing hooks/hooks.json won't affect current session
  • Adding new hook scripts won't be recognized
  • Changing hook commands/prompts won't update
  • Must restart Claude Code: exit and run claude again

To test hook changes:

  1. Edit hook configuration or scripts
  2. Exit Claude Code session
  3. Restart: claude or cc
  4. New hook configuration loads
  5. Test hooks with claude --debug

Hook Validation at Startup

Hooks are validated when Claude Code starts:

  • Invalid JSON in hooks.json causes loading failure
  • Missing scripts cause warnings
  • Syntax errors reported in debug mode

Use /hooks command to review loaded hooks in current session.

Debugging Hooks

Enable Debug Mode

claude --debug

Look for hook registration, execution logs, input/output JSON, and timing information.

Test Hook Scripts

Test command hooks directly:

echo '{"tool_name": "Write", "tool_input": {"file_path": "/test"}}' | \
  bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh

echo "Exit code: $?"

Validate JSON Output

Ensure hooks output valid JSON:

output=$(./your-hook.sh < test-input.json)
echo "$output" | jq .

Quick Reference

Hook Events Summary

Event When Use For
PreToolUse Before tool Validation, modification
PostToolUse After tool Feedback, logging
UserPromptSubmit User input Context, validation
Stop Agent stopping Completeness check
SubagentStop Subagent done Task validation
SessionStart Session begins Context loading
SessionEnd Session ends Cleanup, logging
PreCompact Before compact Preserve context
Notification User notified Logging, reactions

Best Practices

DO:

  • ✅ Use prompt-based hooks for complex logic
  • ✅ Use ${CLAUDE_PLUGIN_ROOT} for portability
  • ✅ Validate all inputs in command hooks
  • ✅ Quote all bash variables
  • ✅ Set appropriate timeouts
  • ✅ Return structured JSON output
  • ✅ Test hooks thoroughly

DON'T:

  • ❌ Use hardcoded paths
  • ❌ Trust user input without validation
  • ❌ Create long-running hooks
  • ❌ Rely on hook execution order
  • ❌ Modify global state unpredictably
  • ❌ Log sensitive information

Additional Resources

Reference Files

For detailed patterns and advanced techniques, consult:

  • references/patterns.md - Common hook patterns (8+ proven patterns)
  • references/migration.md - Migrating from basic to advanced hooks
  • references/advanced.md - Advanced use cases and techniques

Example Hook Scripts

Working examples in examples/:

  • validate-write.sh - File write validation example
  • validate-bash.sh - Bash command validation example
  • load-context.sh - SessionStart context loading example

Utility Scripts

Development tools in scripts/:

  • validate-hook-schema.sh - Validate hooks.json structure and syntax
  • test-hook.sh - Test hooks with sample input before deployment
  • hook-linter.sh - Check hook scripts for common issues and best practices

External Resources

Implementation Workflow

To implement hooks in a plugin:

  1. Identify events to hook into (PreToolUse, Stop, SessionStart, etc.)
  2. Decide between prompt-based (flexible) or command (deterministic) hooks
  3. Write hook configuration in hooks/hooks.json
  4. For command hooks, create hook scripts
  5. Use ${CLAUDE_PLUGIN_ROOT} for all file references
  6. Validate configuration with scripts/validate-hook-schema.sh hooks/hooks.json
  7. Test hooks with scripts/test-hook.sh before deployment
  8. Test in Claude Code with claude --debug
  9. Document hooks in plugin README

Focus on prompt-based hooks for most use cases. Reserve command hooks for performance-critical or deterministic checks.

trang chủ - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-05 23:07
浙ICP备14020137号-1 $bản đồ khách truy cập$