diff --git a/plugins/plugin-dev/skills/agent-development/SKILL.md b/plugins/plugin-dev/skills/agent-development/SKILL.md index f3af0bb..6b1c846 100644 --- a/plugins/plugin-dev/skills/agent-development/SKILL.md +++ b/plugins/plugin-dev/skills/agent-development/SKILL.md @@ -1,6 +1,6 @@ --- name: agent-development -description: This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins. +description: This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", "disallowedTools", "block tools", "agent denylist", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins. --- # Agent Development for Claude Code Plugins @@ -251,6 +251,27 @@ tools: Read, Write, Grep, Bash > **Important:** Agents use `tools` while Skills use `allowed-tools`. The field names differ between component types. For skill tool restrictions, see the `skill-development` skill. +### disallowedTools (optional) + +Denylist complement to `tools`. Block specific tools while allowing all others: + +```yaml +disallowedTools: Bash, Write +``` + +**Format:** Comma-separated tool names + +**Default:** No tools blocked + +| Field | Approach | Use When | +| ----------------- | --------- | --------------------------------------- | +| `tools` | Allowlist | Few tools needed, restrict to minimum | +| `disallowedTools` | Denylist | Most tools needed, block specific risks | + +**Best practice:** Prefer `tools` (allowlist) for tighter security. Use `disallowedTools` when an agent needs broad access but specific tools are dangerous. + +> **Note:** Use one or the other. If both are specified, behavior is undefined. + ### skills (optional) Load specific skills into the agent's context: @@ -470,15 +491,16 @@ Ensure system prompt is complete: ### Frontmatter Fields Summary -| Field | Required | Format | Example | -| -------------- | -------- | -------------------------- | ------------------------ | -| name | Yes | lowercase-hyphens | code-reviewer | -| description | Yes | Text + examples | Use when... ... | -| model | Yes | inherit/sonnet/opus/haiku | inherit | -| color | Yes | Color name | blue | -| tools | No | Comma-separated tool names | Read, Grep | -| skills | No | Array of skill names | [testing, security] | -| permissionMode | No | Permission mode string | acceptEdits | +| Field | Required | Format | Example | +| --------------- | -------- | -------------------------- | ------------------------ | +| name | Yes | lowercase-hyphens | code-reviewer | +| description | Yes | Text + examples | Use when... ... | +| model | Yes | inherit/sonnet/opus/haiku | inherit | +| color | Yes | Color name | blue | +| tools | No | Comma-separated tool names | Read, Grep | +| disallowedTools | No | Comma-separated tool names | Bash, Write | +| skills | No | Array of skill names | [testing, security] | +| permissionMode | No | Permission mode string | acceptEdits | > **Note:** Agents use `tools` to restrict tool access. Skills use `allowed-tools` for the same purpose. The field names differ between component types. diff --git a/plugins/plugin-dev/skills/command-development/SKILL.md b/plugins/plugin-dev/skills/command-development/SKILL.md index c73ffeb..15202b9 100644 --- a/plugins/plugin-dev/skills/command-development/SKILL.md +++ b/plugins/plugin-dev/skills/command-development/SKILL.md @@ -406,6 +406,10 @@ This is intentional. When skill content loads into Claude's context, `[BANG]` fo - Gather project/repository state - Build context-aware workflows +### Load-Time Injection vs Runtime Execution + +The `[BANG]` syntax performs **load-time context injection**: commands execute when the skill or command is loaded, and their output becomes static text in the prompt Claude receives. This is different from Claude choosing to run commands at runtime via the Bash tool. Use `[BANG]` for gathering context (git status, environment variables, config files) that informs Claude's starting state, not for actions Claude should perform during the task. + **Implementation details:** For advanced patterns, environment-specific configurations, and plugin integration, see `references/plugin-features-reference.md` diff --git a/plugins/plugin-dev/skills/hook-development/SKILL.md b/plugins/plugin-dev/skills/hook-development/SKILL.md index 1626ddb..cfdf8b3 100644 --- a/plugins/plugin-dev/skills/hook-development/SKILL.md +++ b/plugins/plugin-dev/skills/hook-development/SKILL.md @@ -1,6 +1,6 @@ --- name: hook-development -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, PermissionRequest, PostToolUse, PostToolUseFailure, Stop, SubagentStop, SubagentStart, Setup, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API. +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", "scoped hooks", "frontmatter hooks", "hook in skill", "hook in agent", "agent hook type", or mentions hook events (PreToolUse, PermissionRequest, PostToolUse, PostToolUseFailure, Stop, SubagentStop, SubagentStart, Setup, 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 @@ -59,6 +59,22 @@ Execute bash commands for deterministic checks: - External tool integrations - Performance-critical checks +### Agent Hooks + +Use an LLM agent for complex, multi-step verification that requires tool access: + +```json +{ + "type": "agent", + "prompt": "Verify all generated code has tests and passes linting", + "timeout": 120 +} +``` + +**Supported events:** Stop, SubagentStop + +Agent hooks spawn a subagent that can use tools (Read, Bash, etc.) for thorough verification — useful when prompt hooks lack sufficient context or tool access. See `references/advanced.md` for patterns. + ## Hook Configuration Formats ### Plugin hooks.json Format @@ -507,6 +523,29 @@ In plugins, define hooks in `hooks/hooks.json` using the **plugin wrapper format **Note:** Plugin hooks use the `{"hooks": {...}}` wrapper format, not the direct settings format. Plugin hooks merge with user's hooks and run in parallel. +## Scoped Hooks in Skill/Agent Frontmatter + +Beyond `hooks.json` (global) and settings (user-level), hooks can be defined directly in skill or agent YAML frontmatter. Scoped hooks activate only when that component is in use: + +```yaml +--- +name: validated-writer +description: Write files with safety checks... +hooks: + PreToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/validate-write.sh" +--- +``` + +**Supported events in frontmatter:** `PreToolUse`, `PostToolUse`, `Stop` + +Scoped hooks use the same event/matcher/hook structure but are lifecycle-bound — they activate when the skill loads and deactivate when it completes. This is ideal for skill-specific validation without affecting other workflows. + +See `references/advanced.md` for detailed syntax and comparison with `hooks.json`. + ## Matchers ### Tool Name Matching diff --git a/plugins/plugin-dev/skills/hook-development/references/advanced.md b/plugins/plugin-dev/skills/hook-development/references/advanced.md index 01f5cfe..ac1a126 100644 --- a/plugins/plugin-dev/skills/hook-development/references/advanced.md +++ b/plugins/plugin-dev/skills/hook-development/references/advanced.md @@ -481,6 +481,146 @@ if [ ! -f "$file_path" ]; then fi ``` +## Scoped Hooks in Skill/Agent Frontmatter + +Hooks can be defined directly in skill or agent YAML frontmatter, scoping them to activate only when that component is in use. + +### Concept + +Unlike `hooks.json` (global, always active when plugin enabled) or settings hooks (user-level), scoped hooks are lifecycle-bound to a specific skill or agent. They activate when the component loads and deactivate when it completes. + +### Format + +The `hooks` field in frontmatter uses the same event/matcher/hook structure as `hooks.json`: + +```yaml +--- +name: secure-writer +description: Write files with safety validation... +hooks: + PreToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/validate-write.sh" + timeout: 10 + PostToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/post-write-check.sh" +--- +``` + +### Supported Events + +Only a subset of hook events apply in frontmatter scope: + +| Event | Purpose in Frontmatter | +| ------------- | -------------------------------------------------------------------------------------------------- | +| `PreToolUse` | Validate or block tool calls during skill execution | +| `PostToolUse` | Run checks after tool execution during skill use | +| `Stop` | Verify completion criteria before skill/agent finishes (auto-converted to SubagentStop for agents) | + +Session-level events (`SessionStart`, `UserPromptSubmit`, `Notification`, etc.) don't apply — they operate at a different lifecycle scope. + +### Comparison with hooks.json + +| Aspect | `hooks.json` | Frontmatter `hooks` | +| -------------- | ------------------------------------------ | --------------------------------------------------- | +| Scope | Global (always active when plugin enabled) | Component-specific (active only during use) | +| Events | All 11+ hook events | PreToolUse, PostToolUse, Stop | +| Location | `hooks/hooks.json` file | YAML frontmatter in SKILL.md or agent .md | +| Merge behavior | Merges with user/project hooks | Merges with global hooks during component lifecycle | + +### Use Cases + +- **Skill-specific validation:** A "database writer" skill that validates SQL before execution +- **Restricted workflows:** A "deploy" skill that checks branch and test status before allowing Bash commands +- **Quality gates:** A "code generator" skill that runs linting after every Write operation +- **Agent safety:** An autonomous agent that validates all Bash commands before execution + +### Both Hook Types Work + +**Command hook** (deterministic script execution): + +```yaml +hooks: + PreToolUse: + - matcher: Bash + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/check-safety.sh" +``` + +**Prompt hook** (LLM evaluation): + +```yaml +hooks: + Stop: + - hooks: + - type: prompt + prompt: 'Verify all generated code has tests. Return {"decision": "stop"} if satisfied or {"decision": "continue", "reason": "missing tests"} if not.' +``` + +## Agent Hook Type + +The `agent` hook type spawns a subagent for complex, multi-step verification workflows that require tool access. + +### Concept + +While `command` hooks execute bash scripts and `prompt` hooks evaluate a single LLM prompt, `agent` hooks create a full subagent that can use tools (Read, Bash, Grep, etc.) to perform thorough verification. This is the most powerful but most expensive hook type. + +### Configuration + +```json +{ + "type": "agent", + "prompt": "Verify that all generated code has tests and passes linting. Check each modified file.", + "timeout": 120 +} +``` + +### Supported Events + +Agent hooks are supported on **Stop** and **SubagentStop** events only. They aren't suitable for PreToolUse (too slow) or session-level events. + +### When to Use Agent Hooks + +| Hook Type | Speed | Capability | Best For | +| --------- | --------------- | --------------------- | --------------------------------------------- | +| `command` | Fast (~1-5s) | Bash scripts only | Deterministic checks, file validation | +| `prompt` | Medium (~5-15s) | Single LLM evaluation | Context-aware decisions, flexible logic | +| `agent` | Slow (~30-120s) | Multi-step with tools | Comprehensive verification, multi-file checks | + +Use agent hooks when: + +- Verification requires reading multiple files +- You need to run commands and analyze their output +- Single-prompt evaluation is insufficient +- Completion criteria are complex and multi-faceted + +### Example: Comprehensive Completion Check + +```json +{ + "Stop": [ + { + "matcher": "*", + "hooks": [ + { + "type": "agent", + "prompt": "Before approving task completion, verify: 1) All modified files have corresponding tests, 2) Tests pass (run them), 3) No linting errors exist. Report findings and return approve/block decision.", + "timeout": 120 + } + ] + } + ] +} +``` + +The agent will autonomously read files, run tests, check linting, and make a comprehensive decision about whether to allow the main agent to stop. + ## Conclusion Advanced hook patterns enable sophisticated automation while maintaining reliability and performance. Use these techniques when basic hooks are insufficient, but always prioritize simplicity and maintainability. diff --git a/plugins/plugin-dev/skills/mcp-integration/SKILL.md b/plugins/plugin-dev/skills/mcp-integration/SKILL.md index c1966ac..4715185 100644 --- a/plugins/plugin-dev/skills/mcp-integration/SKILL.md +++ b/plugins/plugin-dev/skills/mcp-integration/SKILL.md @@ -1,6 +1,6 @@ --- name: mcp-integration -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", discusses MCP server types (SSE, stdio, HTTP, WebSocket), or asks to "find MCP server", "discover MCP servers", "what MCP servers exist", "recommend MCP server for [service]". Provides comprehensive guidance for integrating Model Context Protocol servers into Claude Code plugins for external tool and service integration. +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", discusses MCP server types (SSE, stdio, HTTP, WebSocket), or asks to "find MCP server", "discover MCP servers", "what MCP servers exist", "recommend MCP server for [service]", "MCP prompts", "MCP prompts as commands", "tool search", "tool search threshold". 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 @@ -261,6 +261,21 @@ Claude will fetch the resource content and include it in context. - **https://** - HTTP resources - **Custom protocols** - Server-specific (postgres://, s3://, etc.) +## MCP Prompts as Commands + +MCP servers can expose **prompts** that appear as slash commands in Claude Code: + +**Format:** `/mcp__servername__promptname` + +**Example:** + +- Server `github` exposes prompt `create-pr` +- Available as: `/mcp__github__create-pr` + +MCP prompts appear alongside regular commands in the `/` menu. They accept arguments and execute the server's prompt template with Claude. This enables MCP servers to provide guided workflows beyond simple tool calls. + +**Plugin design note:** If your MCP server exposes prompts, document their names and expected arguments in your plugin README so users can discover them. + ## Tool Search For MCP servers with many tools, use Tool Search to find relevant tools: @@ -277,6 +292,16 @@ For MCP servers with many tools, use Tool Search to find relevant tools: 2. Search by natural language or partial names 3. Get filtered list of matching tools +### Auto-Enable Behavior + +Tool Search activates automatically when MCP servers collectively provide more tools than fit efficiently in Claude's context window (default threshold: 10% of context). Instead of loading all tool descriptions upfront, Claude searches for relevant tools on-demand. + +**Plugin design implications:** + +- **Many-tool servers**: Tools may not be immediately visible; use descriptive tool names and descriptions +- **Documentation**: Note tool search behavior in README if your server provides 20+ tools +- **Environment control**: `ENABLE_TOOL_SEARCH=auto:5` (custom 5% threshold) or `ENABLE_TOOL_SEARCH=false` (disable) + This feature is automatic - just ask Claude about available tools or describe what you want to do. ### Using MCP Tools in Commands diff --git a/plugins/plugin-dev/skills/mcp-integration/references/tool-usage.md b/plugins/plugin-dev/skills/mcp-integration/references/tool-usage.md index bd61bfe..ca0f0d3 100644 --- a/plugins/plugin-dev/skills/mcp-integration/references/tool-usage.md +++ b/plugins/plugin-dev/skills/mcp-integration/references/tool-usage.md @@ -585,3 +585,39 @@ Effective MCP tool usage requires: 6. **Testing thoroughly** before deployment Follow these patterns for robust MCP tool integration in your plugin commands and agents. + +## MCP Prompts as Commands + +Beyond tools and resources, MCP servers can expose **prompts** — pre-defined instruction templates that appear as slash commands in Claude Code. + +### How Prompts Work + +When an MCP server declares prompts via the MCP protocol, Claude Code automatically registers them as slash commands: + +- **Format:** `/mcp__servername__promptname` +- **Discovery:** Prompts appear in the `/` autocomplete menu alongside regular commands +- **Arguments:** Prompts can accept arguments defined by the server's prompt schema + +### Integration with Plugin Commands + +If your plugin bundles an MCP server that exposes prompts, those prompts become available when the plugin is installed. This provides another mechanism for guided workflows: + +```markdown +# Example: Plugin README documenting MCP prompts + +## Available MCP Prompts + +After installing this plugin, the following MCP prompts are available: + +- `/mcp__myserver__create-report` - Generate a structured report +- `/mcp__myserver__analyze-data` - Run data analysis with guided inputs +``` + +### When to Use MCP Prompts vs Plugin Commands + +| Approach | Best For | +| --- | --- | +| MCP prompts | Server-defined workflows, dynamic templates from external services | +| Plugin commands | Static workflows, plugin-specific logic, complex prompt composition | + +**Tip:** MCP prompts are ideal when the workflow logic lives on the server side and may change independently of the plugin. Plugin commands are better when you want full control over the prompt content. diff --git a/plugins/plugin-dev/skills/plugin-settings/SKILL.md b/plugins/plugin-dev/skills/plugin-settings/SKILL.md index 9e1e9ab..4a17f72 100644 --- a/plugins/plugin-dev/skills/plugin-settings/SKILL.md +++ b/plugins/plugin-dev/skills/plugin-settings/SKILL.md @@ -1,6 +1,6 @@ --- name: plugin-settings -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. +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", "CLAUDE.md imports", "rules system", "memory hierarchy", "memory priority", 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 @@ -525,6 +525,14 @@ if [[ ! -f ".claude/my-plugin.local.md" ]]; then fi ``` +## Memory & Rules Context + +Plugin settings files (`.local.md`) exist alongside Claude Code's broader memory and rules system. Understanding how CLAUDE.md imports, `.claude/rules/` path-specific rules, and the memory priority hierarchy interact with plugin content helps design plugins that complement rather than conflict with user configurations. + +See `references/memory-rules-system.md` for the full priority hierarchy, import syntax, and design implications. + +--- + ## Additional Resources ### Reference Files @@ -533,6 +541,7 @@ 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 +- **`references/memory-rules-system.md`** - How plugin content interacts with CLAUDE.md, rules, and the memory hierarchy ### Example Files diff --git a/plugins/plugin-dev/skills/plugin-settings/references/memory-rules-system.md b/plugins/plugin-dev/skills/plugin-settings/references/memory-rules-system.md new file mode 100644 index 0000000..4189df3 --- /dev/null +++ b/plugins/plugin-dev/skills/plugin-settings/references/memory-rules-system.md @@ -0,0 +1,195 @@ +# Memory & Rules System Interaction + +Claude Code has a layered memory and rules system that plugins interact with. Understanding this system helps plugin developers design components that complement (rather than conflict with) the user's existing configuration. + +## CLAUDE.md Memory Files + +### What They Are + +CLAUDE.md files provide persistent instructions that Claude reads at the start of every session. They contain project context, coding standards, and behavioral guidance. + +### File Locations and Priority + +Memory files are loaded in priority order (highest first): + +| Priority | Location | Scope | +| ----------- | ------------------------------------ | ----------------------------- | +| 1 (highest) | Managed policy (system paths) | Organization-wide | +| 2 | `.claude/CLAUDE.md` or `./CLAUDE.md` | Project (shared via git) | +| 3 | `.claude/rules/*.md` | Project rules (modular) | +| 4 | `~/.claude/CLAUDE.md` | User (personal, all projects) | +| 5 (lowest) | `.claude/CLAUDE.local.md` | Project local (gitignored) | + +Higher-priority instructions take precedence when there are conflicts. + +**Why local is lowest priority:** Unlike typical configuration systems where ".local" means "override", Claude Code's `.local.md` files are for personal, project-specific notes and preferences that shouldn't override team standards. The hierarchy ensures organizational policy (managed) > team standards (project) > personal preferences (user/local). + +### Import Syntax + +CLAUDE.md files can import other files: + +```markdown +# Project Instructions + +@docs/coding-standards.md +@docs/api-conventions.md +``` + +**Rules:** + +- Paths are relative to the importing file +- Absolute paths are also supported +- Maximum recursion depth: 5 hops +- Imports are NOT evaluated inside code blocks or inline code spans +- Circular imports are detected and handled + +### Creating CLAUDE.md + +The `/init` command generates a starter CLAUDE.md by analyzing the codebase. Alternatively, create one manually: + +```markdown +# Project Name + +## Code Style + +- Use TypeScript strict mode +- Follow Prettier defaults + +## Architecture + +- Components in src/components/ +- API routes in src/api/ + +## Testing + +- Write tests for all new features +- Use Jest with React Testing Library +``` + +## Rules System + +### What Rules Are + +Rules are modular instruction files in `.claude/rules/` that can optionally target specific file patterns. They provide focused guidance that loads contextually. + +### File Structure + +``` +.claude/ +└── rules/ + ├── testing.md # Applies globally + ├── api-patterns.md # Applies globally + └── typescript.md # Path-specific (see below) +``` + +### Path-Specific Rules + +Rules can target specific files using YAML frontmatter with glob patterns: + +```markdown +--- +paths: + - "src/**/*.ts" + - "lib/**/*.ts" +--- + +Use strict TypeScript patterns: + +- No `any` types +- Explicit return types on all public functions +- Use discriminated unions over type assertions +``` + +**Glob support:** + +- Standard patterns: `*`, `?`, `**` +- Brace expansion: `src/**/*.{ts,tsx}` +- Multiple patterns in the `paths` array +- Patterns match against relative paths from project root + +### When Rules Load + +Rules load automatically based on file context: + +- Global rules (no `paths` frontmatter): Always loaded +- Path-specific rules: Loaded when Claude accesses matching files +- Rules in subdirectories: Organized by topic, all discovered automatically + +### User-Level Rules + +Personal rules in `~/.claude/rules/` apply across all projects with lower priority than project rules. + +## How Plugin Content Fits + +### Plugin Content Priority + +Plugin content loads differently from the memory/rules hierarchy: + +| Content Type | How It Loads | Priority Context | +| --------------------- | -------------------------------------- | ----------------------------------- | +| Skill descriptions | As tool definitions (always available) | Independent of memory hierarchy | +| Skill body (SKILL.md) | When skill triggers | Independent of memory hierarchy | +| Agent definitions | As subagent configs | Independent of memory hierarchy | +| Hook configurations | Merge with user/project hooks | Parallel execution with other hooks | +| MCP servers | As tool providers | Independent of memory hierarchy | + +Plugin content doesn't directly compete with CLAUDE.md for priority — it operates through different mechanisms (tool definitions, hooks, MCP tools). + +### Where They Overlap + +Conflicts can arise when: + +1. **CLAUDE.md instructions contradict plugin skill guidance** — CLAUDE.md has implicit priority as it's always in context +2. **Project rules specify patterns that conflict with plugin hooks** — Both apply; hooks enforce, rules guide +3. **User settings restrict tools that plugins need** — User settings win; plugins should document requirements + +## Design Implications for Plugin Developers + +### Don't Duplicate CLAUDE.md Content + +If a project's CLAUDE.md already specifies coding standards, your plugin skills shouldn't re-specify them. Instead, reference them: + +```markdown +Follow the project's coding standards (see CLAUDE.md) while applying +the additional [domain-specific] patterns below... +``` + +### Use Rules for File-Type Guidance + +If your plugin needs file-type-specific behavior, consider whether it belongs as: + +- **A rule** (`.claude/rules/`): For guidance that should always apply to certain file types +- **A skill**: For knowledge that's invoked on demand +- **A hook**: For enforcement that must happen every time + +### Understand Override Behavior + +Users can override plugin behavior through: + +- CLAUDE.md instructions (higher priority context) +- Settings that restrict tools (`permissions.deny`) +- Disabling plugin hooks via settings + +Design plugins to be graceful when overridden. Document what settings affect plugin behavior. + +### Plugin Settings (.local.md) vs Rules + +Plugin settings (`.claude/plugin-name.local.md`) and rules (`.claude/rules/`) serve different purposes: + +| Aspect | Plugin .local.md | .claude/rules/ | +| ---------- | ----------------------------- | ------------------------------------- | +| Purpose | Plugin-specific configuration | Project-wide guidance | +| Format | YAML frontmatter + markdown | Optional paths frontmatter + markdown | +| Scope | Single plugin | All Claude interactions | +| Managed by | User configuring plugin | Project maintainers | +| In git | No (gitignored) | Yes (shared with team) | + +### Test with Various Configurations + +Test your plugin with: + +1. Empty CLAUDE.md (no project context) +2. Detailed CLAUDE.md (potential conflicts) +3. Path-specific rules (ensure hooks don't conflict) +4. User-level rules (personal preferences) +5. Managed settings (enterprise restrictions) diff --git a/plugins/plugin-dev/skills/plugin-structure/SKILL.md b/plugins/plugin-dev/skills/plugin-structure/SKILL.md index 869273d..96741db 100644 --- a/plugins/plugin-dev/skills/plugin-structure/SKILL.md +++ b/plugins/plugin-dev/skills/plugin-structure/SKILL.md @@ -1,6 +1,6 @@ --- name: plugin-structure -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", "add lspServers", "configure auto-discovery", or needs guidance on plugin directory layout, manifest configuration, component organization, file naming conventions, or Claude Code plugin architecture best practices. +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", "add lspServers", "configure auto-discovery", "headless mode", "CI mode", "plugin in CI", "github actions", "plugin caching", "plugin CLI", "install plugin", "installation scope", "auto-update", 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 @@ -590,6 +590,14 @@ Or use `--plugin-dir` for testing without installation: claude --plugin-dir /path/to/plugin ``` +## Runtime Contexts + +Plugins behave differently depending on the runtime context. Interactive sessions support slash commands and user prompts; headless mode (`claude -p`) and GitHub Actions provide non-interactive environments where some features are unavailable. + +- **Headless/CI mode:** See `references/headless-ci-mode.md` for designing plugins that work in `claude -p` and CI pipelines +- **GitHub Actions:** See `references/github-actions.md` for integrating plugins with `claude-code-action@v1` +- **Advanced topics:** See `references/advanced-topics.md` for caching behavior, installation scopes, CLI management, keybindings, status line, and auto-update behavior + ## Troubleshooting **Component not loading**: @@ -628,6 +636,9 @@ claude --plugin-dir /path/to/plugin - **`references/component-patterns.md`** - Detailed patterns for each component type - **`references/manifest-reference.md`** - Complete plugin.json field reference +- **`references/headless-ci-mode.md`** - Headless and CI mode plugin compatibility +- **`references/github-actions.md`** - GitHub Actions integration for plugins +- **`references/advanced-topics.md`** - Caching, installation scopes, CLI commands, and more ### Example Files diff --git a/plugins/plugin-dev/skills/plugin-structure/references/advanced-topics.md b/plugins/plugin-dev/skills/plugin-structure/references/advanced-topics.md new file mode 100644 index 0000000..8891cb4 --- /dev/null +++ b/plugins/plugin-dev/skills/plugin-structure/references/advanced-topics.md @@ -0,0 +1,274 @@ +# Advanced Plugin Topics + +This reference covers specialized topics that plugin developers may encounter in advanced use cases. Each section is self-contained. + +## Keybindings Plugin Context + +Claude Code's keybindings system (`~/.claude/keybindings.json`) includes a `plugin:` context with actions for plugin management: + +| Action | Description | +| ---------------- | ----------------------- | +| `plugin:toggle` | Enable/disable a plugin | +| `plugin:install` | Install a plugin | + +**Configuration:** + +```json +{ + "bindings": [ + { + "context": "Plugin", + "bindings": { + "ctrl+p": "plugin:toggle" + } + } + ] +} +``` + +**Plugin developer relevance:** Low. This is user-facing configuration. Plugins cannot define custom keybindings. If your plugin has frequently used commands, document keyboard shortcuts users can configure. + +## Status Line Integration + +Plugins can provide status line scripts that display contextual information in the Claude Code footer. + +### How It Works + +Users configure a status line command in `.claude/settings.json`: + +```json +{ + "statusLine": { + "type": "command", + "command": "~/.claude/statusline.sh", + "padding": 0 + } +} +``` + +The script receives JSON via stdin with session context (model, cost, tokens, workspace info) and outputs a single line of text (ANSI colors supported). + +### Available Data + +The JSON input includes: + +- `model.display_name` — Current model name +- `cost.total_cost_usd` — Session cost +- `cost.total_lines_added` / `total_lines_removed` — Code changes +- `context_window.used_percentage` — Context usage +- `context_window.total_input_tokens` / `total_output_tokens` — Token counts +- `workspace.current_dir` / `project_dir` — Directory info +- `version` — Claude Code version + +### Plugin Use Case + +A plugin could bundle a status line script that displays plugin-specific information: + +```bash +#!/bin/bash +input=$(cat) +model=$(echo "$input" | jq -r '.model.display_name') +cost=$(echo "$input" | jq -r '.cost.total_cost_usd') +echo "[$model] \$${cost}" +``` + +**Note:** Users must manually configure their status line to use the plugin's script. There is no auto-configuration mechanism. + +## Claude Code as MCP Server + +Claude Code can itself act as an MCP server, exposing its capabilities to other MCP clients: + +```bash +claude mcp serve +``` + +**Plugin developer relevance:** Edge case. This is useful when building toolchains where one Claude Code instance needs to communicate with another, or when integrating Claude Code into a larger MCP-based system. Plugin MCP servers are unaffected by this feature. + +## MCP `@` Resource Reference Syntax + +Users can reference MCP resources inline using the `@` syntax: + +``` +@server-name:protocol://resource/path +``` + +### Common Patterns + +| Syntax | Example | +| ------------- | ------------------------------------------- | +| File resource | `@filesystem:file:///path/to/file.txt` | +| Database | `@database:postgres://localhost/mydb/users` | +| GitHub | `@github:https://github.com/user/repo` | +| Custom | `@myserver:custom://resource/id` | + +### Discovery + +Type `@` in Claude Code to see available resources from connected MCP servers. + +### Plugin Design Note + +If your plugin's MCP server exposes resources, document the available resource URIs and protocols in your README. Users can then reference them with `@plugin-server:protocol://path`. + +## Hook Agent Type Details + +The `agent` hook type (covered briefly in the hook-development SKILL.md) spawns a full subagent for complex verification workflows. + +For comprehensive coverage including configuration, behavior, supported events, when to use agent hooks, and detailed examples, see the hook-development skill's `references/advanced.md` file. + +**Quick summary:** Agent hooks spawn a subagent with full tool access (Read, Bash, Grep, etc.) for multi-step verification. They're significantly slower (30-120 seconds) but more capable than command or prompt hooks. Only supported on `Stop` and `SubagentStop` events. + +## Auto-Update Behavior + +### Default Behavior + +- **Official marketplaces:** Auto-update enabled by default +- **Third-party/local marketplaces:** Auto-update disabled by default + +### Environment Variables + +| Variable | Effect | +| ------------------------------- | -------------------------------------- | +| `DISABLE_AUTOUPDATER=true` | Disable all auto-updates | +| `FORCE_AUTOUPDATE_PLUGINS=true` | Force auto-update for all marketplaces | + +### Plugin Versioning Implications + +- Use semantic versioning (`MAJOR.MINOR.PATCH`) +- Breaking changes should bump MAJOR version +- Users on auto-update receive MINOR/PATCH changes automatically +- Document breaking changes in CHANGELOG +- Consider pre-release versions (`2.0.0-beta.1`) for testing + +## Plugin Caching + +### How Caching Works + +When a plugin is installed, Claude Code copies plugin content to a cache directory. Plugins run from the cache, not from their source location. + +### Key Implications + +1. **No `../` paths:** Plugins cannot reference files outside their directory via `../` — the cache copy doesn't include parent directories +2. **`${CLAUDE_PLUGIN_ROOT}` resolves to cache:** The variable points to the cached copy, not the source +3. **Symlinks are followed:** Symlinks within the plugin directory are resolved during the copy, so the target content is included + +### Workarounds for External Files + +If your plugin needs content from outside its directory: + +- **Symlinks:** Create symlinks to external files within the plugin directory (followed during cache copy) +- **Restructure:** Move shared content into the plugin directory +- **Environment variables:** Reference external paths via environment variables, not file paths +- **MCP servers:** Use MCP tools to access external resources at runtime + +### Cache Management + +Users can clear the plugin cache: + +```bash +rm -rf ~/.claude/plugins/cache +``` + +This forces re-caching on next session start. + +## Plugin CLI Management Commands + +Users manage plugins through CLI commands (or the `/plugin` interactive interface): + +### Installation + +```bash +# Install from marketplace +claude plugin install plugin-name@marketplace-name + +# Installation scopes +claude plugin install plugin-name@marketplace --scope user # Personal (default) +claude plugin install plugin-name@marketplace --scope project # Team (in .claude/settings.json) +claude plugin install plugin-name@marketplace --scope local # Personal project (gitignored) +``` + +### Management + +```bash +# List installed plugins +claude plugin list + +# Enable/disable without uninstalling +claude plugin enable plugin-name@marketplace +claude plugin disable plugin-name@marketplace + +# Update to latest version +claude plugin update plugin-name@marketplace + +# Remove completely +claude plugin uninstall plugin-name@marketplace +``` + +### Marketplace Management + +```bash +# Add a marketplace +claude plugin marketplace add owner/repo # GitHub +claude plugin marketplace add https://gitlab.com/org/repo.git # Git URL +claude plugin marketplace add ./local-path # Local + +# List/update/remove +claude plugin marketplace list +claude plugin marketplace update marketplace-name +claude plugin marketplace remove marketplace-name +``` + +### Plugin Developer Note + +Document the exact install command in your README: + +```markdown +## Installation + +\`\`\`bash +claude plugin install my-plugin@my-marketplace +\`\`\` +``` + +## Installation Scopes + +Plugins can be installed at different scopes, affecting who has access: + +| Scope | Location | Shared | Gitignored | Use Case | +| --------- | ----------------------------- | --------- | ---------- | ------------------------ | +| `user` | `~/.claude/settings.json` | No | N/A | Personal tools (default) | +| `project` | `.claude/settings.json` | Yes (git) | No | Team standards | +| `local` | `.claude/settings.local.json` | No | Yes | Personal project tools | +| `managed` | System paths | Yes (MDM) | N/A | Enterprise enforcement | + +### Scope Precedence + +When the same plugin is configured at multiple scopes, local overrides project, which overrides user. + +### Team Plugin Distribution + +For team plugins, install at `project` scope and commit `.claude/settings.json`: + +```json +{ + "enabledPlugins": { + "my-plugin@my-marketplace": true + } +} +``` + +Team members get the plugin when they clone the repo. + +### Enterprise Plugin Control + +Organizations can use managed settings to: + +- **Allowlist marketplaces:** `strictKnownMarketplaces` restricts which marketplaces users can add +- **Force plugins:** Pre-configure required plugins via managed settings +- **Block plugins:** Prevent specific plugins from being installed + +### Plugin Developer Implications + +- Document recommended scope in README +- Test plugin at both user and project scopes +- For team plugins, provide `.claude/settings.json` snippets +- Note that managed settings can override plugin availability diff --git a/plugins/plugin-dev/skills/plugin-structure/references/github-actions.md b/plugins/plugin-dev/skills/plugin-structure/references/github-actions.md new file mode 100644 index 0000000..208e5fa --- /dev/null +++ b/plugins/plugin-dev/skills/plugin-structure/references/github-actions.md @@ -0,0 +1,232 @@ +# GitHub Actions Integration for Plugins + +Plugins interact with GitHub Actions through `claude-code-action`, Anthropic's official action for running Claude Code in CI workflows. Understanding this integration helps plugin developers ensure their plugins work seamlessly in automated pipelines. + +## Overview + +The `claude-code-action@v1` runs Claude Code inside GitHub Actions, enabling: + +- Automated code review on PRs +- Issue implementation from comments +- Custom automation triggered by @claude mentions +- Scheduled analysis and reporting + +## Setup + +### Quick Setup + +From inside Claude Code: + +```bash +/install-github-app +``` + +This guides through installing the Claude GitHub app and configuring workflows. + +### Manual Setup + +1. Install the Claude GitHub App: `https://github.com/apps/claude` +2. Add `ANTHROPIC_API_KEY` to repository secrets +3. Create workflow file at `.github/workflows/claude.yml` + +### Basic Workflow + +```yaml +name: Claude Code +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + +jobs: + claude: + runs-on: ubuntu-latest + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} +``` + +## How Plugins Work in Actions + +### CLAUDE.md Integration + +The most direct way plugins interact with CI is through CLAUDE.md. Project-level instructions (`.claude/CLAUDE.md`) load automatically in CI runs, providing: + +- Code style requirements +- Review criteria +- Project-specific rules +- Plugin references + +### Hooks in CI + +Plugin hooks execute in the CI environment: + +- **Command hooks:** Run normally (ensure scripts are executable and dependencies available) +- **Prompt hooks:** Work as expected +- **SessionStart hooks:** Fire at the beginning of each CI run +- **Environment:** `$CI=true` is set, use for conditional logic + +**CI-aware hook example:** + +```bash +#!/bin/bash +# Skip interactive checks in CI +if [ "$CI" = "true" ]; then + echo '{"continue": true}' + exit 0 +fi +# Full validation in local development +# ... +``` + +### Skills via prompt Parameter + +Reference plugin skills in the workflow's `prompt` parameter: + +```yaml +- uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: "Review this PR for security issues following our coding standards" + claude_args: "--max-turns 15" +``` + +Since slash commands don't work in headless mode, describe the task instead. If the skill has `user-invocable: false`, Claude will use it automatically based on context. + +## Configuration Options + +### Key Parameters + +| Parameter | Purpose | Example | +| ------------------- | ----------------------- | -------------------------------------- | +| `prompt` | Instructions for Claude | `"Review this PR"` | +| `claude_args` | CLI arguments | `"--max-turns 10 --model haiku"` | +| `anthropic_api_key` | API key secret | `${{ secrets.ANTHROPIC_API_KEY }}` | +| `github_token` | GitHub API access | `${{ secrets.GITHUB_TOKEN }}` | +| `trigger_phrase` | Custom trigger | `"@review-bot"` (default: `"@claude"`) | + +### claude_args for Plugin Control + +Pass CLI flags through `claude_args`: + +```yaml +claude_args: >- + --max-turns 20 + --model claude-sonnet-4-5-20250929 + --allowedTools "Read,Grep,Glob,Bash(npm:*)" +``` + +### Custom Trigger Phrases + +Change the default `@claude` trigger: + +```yaml +trigger_phrase: "@security-review" +``` + +Users then mention `@security-review` in PR comments to trigger the workflow. + +## Provider Configurations + +### AWS Bedrock + +```yaml +- uses: anthropics/claude-code-action@v1 + with: + use_bedrock: "true" + claude_args: "--model us.anthropic.claude-sonnet-4-5-20250929-v1:0" + env: + AWS_ROLE_TO_ASSUME: ${{ secrets.AWS_ROLE_TO_ASSUME }} + AWS_REGION: us-east-1 +``` + +Requires AWS OIDC configuration with Bedrock permissions. + +### Google Vertex AI + +```yaml +- uses: anthropics/claude-code-action@v1 + with: + use_vertex: "true" + claude_args: "--model claude-sonnet-4@20250514" + env: + ANTHROPIC_VERTEX_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }} + CLOUD_ML_REGION: us-east5 +``` + +Requires GCP Workload Identity Federation. + +## Cost Management + +### Limit Turns + +```yaml +claude_args: "--max-turns 10" +``` + +Each tool call is one turn. Start low and increase as needed. + +### Use Cheaper Models + +```yaml +claude_args: "--model haiku" +``` + +Use Haiku for routine checks, Sonnet for standard reviews, Opus for complex analysis. + +### Set Workflow Timeouts + +```yaml +jobs: + claude: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: anthropics/claude-code-action@v1 + # ... +``` + +### Restrict Tool Access + +```yaml +claude_args: "--allowedTools 'Read,Grep,Glob'" +``` + +Read-only tools prevent expensive write/execute loops. + +## Plugin Design for CI + +### Document CI Workflows + +Include example workflow snippets in your plugin README: + +```markdown +## GitHub Actions Usage + +Add to `.github/workflows/claude.yml`: + +\`\`\`yaml +- uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: "Analyze code using [your-plugin] standards" + claude_args: "--max-turns 15 --allowedTools 'Read,Grep,Glob'" +\`\`\` +``` + +### Ensure CI Compatibility + +- Test hooks with `CI=true` environment variable +- Ensure scripts don't require interactive input +- Handle missing dependencies gracefully (not all CI images have `jq`, etc.) +- Use `${CLAUDE_PLUGIN_ROOT}` for all paths (cache directories differ in CI) + +### MCP Servers in CI + +MCP servers bundled with plugins start in CI, but: + +- OAuth-based servers won't have tokens (configure environment variables instead) +- Local stdio servers need their dependencies installed in the CI image +- Document required CI setup in README diff --git a/plugins/plugin-dev/skills/plugin-structure/references/headless-ci-mode.md b/plugins/plugin-dev/skills/plugin-structure/references/headless-ci-mode.md new file mode 100644 index 0000000..3f2a382 --- /dev/null +++ b/plugins/plugin-dev/skills/plugin-structure/references/headless-ci-mode.md @@ -0,0 +1,193 @@ +# Headless & CI Mode Plugin Compatibility + +Plugins behave differently in headless mode (`claude -p`) versus interactive sessions. Understanding these differences is critical for building plugins that work reliably across all runtime contexts. + +## Headless Mode Basics + +Headless mode executes Claude Code as a single-shot command-line tool: + +```bash +claude -p "Analyze this codebase for security issues" --allowedTools "Read,Grep,Glob" +``` + +### What Works in Headless Mode + +- **Hooks:** Command hooks execute normally. Prompt hooks work for supported events. +- **MCP servers:** Start and connect as usual. Tools are available. +- **CLAUDE.md:** Project and user memory files load normally. +- **Agents:** Can be spawned via Task tool during execution. +- **Skills (as context):** Skill content with `user-invocable: false` loads into context and is available for Claude to use. + +### What Does NOT Work in Headless Mode + +- **Slash commands:** `/skill-name` invocation requires an interactive session. Skills cannot be invoked via slash commands in `-p` mode. +- **Interactive prompts:** `AskUserQuestion` tool is not available — there's no user to answer. +- **Skill tool (manual):** Users can't type `/` to invoke skills. Instead, describe the task and let Claude use the skill content if loaded. + +### Workaround for Skills + +Instead of invoking `/review` in headless mode, describe the task: + +```bash +# Won't work: +claude -p "/review" + +# Works — describe what you want: +claude -p "Review the codebase for code quality issues" +``` + +If the skill has `user-invocable: false` and is loaded via plugin, Claude can still use its knowledge automatically. + +## Permission Control + +### --allowedTools + +Auto-approve specific tools without interactive prompts: + +```bash +claude -p "Fix the bug" --allowedTools "Read,Write,Edit,Bash(git *)" +``` + +**Permission rule syntax:** + +| Pattern | Matches | +| ---------------------- | ------------------------------------------------------------ | +| `Read` | All Read tool calls | +| `Bash(git *)` | Bash commands starting with "git " (prefix match with space) | +| `mcp__*` | All MCP tool calls | +| `mcp__plugin_myplug_*` | Tools from a specific plugin's MCP server | +| `Write,Edit` | Multiple tools (comma-separated) | + +**Plugin design tip:** Document recommended `--allowedTools` values in your plugin README for CI usage. + +### --max-turns + +Limit autonomous tool-use iterations to control cost and runtime: + +```bash +claude -p "Run tests and fix failures" --allowedTools "Read,Edit,Bash" --max-turns 10 +``` + +Each tool call counts as one turn. Without this limit, Claude may iterate indefinitely on complex tasks. + +## Structured Output + +### JSON Output + +Get machine-readable responses: + +```bash +claude -p "List all TODO comments" --output-format json +``` + +Returns: + +```json +{ + "result": "Found 5 TODO comments...", + "session_id": "abc123", + "metadata": { ... } +} +``` + +### JSON Schema Validation + +Enforce a specific output structure: + +```bash +claude -p "Extract function signatures from auth.py" \ + --output-format json \ + --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' +``` + +**Plugin design tip:** If your plugin provides analysis workflows, document example JSON schemas users can use for structured CI output. + +## System Prompt Interaction + +### --append-system-prompt + +Add instructions alongside the default system prompt (and any loaded plugin content): + +```bash +claude -p "Review code" --append-system-prompt "Focus on security vulnerabilities only" +``` + +Plugin skill content loads before system prompt overrides. The append adds to (not replaces) existing context. + +### --system-prompt + +Replace the default system prompt entirely: + +```bash +claude -p "Analyze" --system-prompt "You are a security auditor..." +``` + +**Caution:** This replaces the default prompt but plugin content still loads. The interaction between `--system-prompt` and plugin skills may produce unexpected behavior. + +## Session Management + +### Continue Last Session + +```bash +claude -p "What was the last change you made?" --continue +``` + +### Resume Specific Session + +```bash +claude -p "Continue fixing the auth bug" --resume "$SESSION_ID" +``` + +Plugin state (hooks, MCP servers, skill context) reloads when resuming a session. + +## Plugin Design Guidelines for CI Compatibility + +### 1. Test in Headless Mode + +```bash +# Test your plugin works in non-interactive mode +claude -p "Run the plugin's primary workflow" \ + --plugin-dir /path/to/plugin \ + --allowedTools "Read,Write,Edit,Bash" +``` + +### 2. Avoid Interactive-Only Patterns + +- Don't rely on `AskUserQuestion` for critical workflows +- Provide sensible defaults when user input is unavailable +- Design hooks that work without user confirmation + +### 3. Document CI Usage + +Include a CI section in your plugin README: + +```markdown +## CI/Headless Usage + +This plugin works in headless mode. Example: + +\`\`\`bash +claude -p "Run security audit" \ + --allowedTools "Read,Grep,Glob,Bash(npm:\*)" \ + --max-turns 20 \ + --output-format json +\`\`\` +``` + +### 4. Handle Missing Environment Gracefully + +In CI environments, some tools or context may be unavailable: + +- MCP servers may not have authentication tokens +- Git history may be shallow clones +- Environment variables may differ from local dev + +Design hooks and skills to handle these cases without failing hard. + +### 5. Cost-Conscious Design + +CI runs can accumulate significant API costs. Help users control spending: + +- Recommend `--max-turns` values for common workflows +- Use `haiku` model for simple analysis skills +- Document expected token usage for key workflows diff --git a/plugins/plugin-dev/skills/skill-development/SKILL.md b/plugins/plugin-dev/skills/skill-development/SKILL.md index 1797d6f..c577616 100644 --- a/plugins/plugin-dev/skills/skill-development/SKILL.md +++ b/plugins/plugin-dev/skills/skill-development/SKILL.md @@ -1,6 +1,6 @@ --- name: skill-development -description: This skill should be used when the user asks to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill content", "SKILL.md format", "skill frontmatter", "skill triggers", "trigger phrases for skills", "progressive disclosure", "skill references folder", "skill examples folder", "validate skill", or needs guidance on skill structure, file organization, writing style, or skill development best practices for Claude Code plugins. +description: This skill should be used when the user asks to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill content", "SKILL.md format", "skill frontmatter", "skill triggers", "trigger phrases for skills", "progressive disclosure", "skill references folder", "skill examples folder", "validate skill", "skill model field", "skill hooks", "scoped hooks in skill", "visibility budget", "context budget", "SLASH_COMMAND_TOOL_CHAR_BUDGET", or needs guidance on skill structure, file organization, writing style, or skill development best practices for Claude Code plugins. --- # Skill Development for Claude Code Plugins @@ -184,6 +184,45 @@ Use for skills that should only be manually invoked by users, such as: | `user-invocable: false` | Hidden | Allowed | Yes | | `disable-model-invocation: true` | Visible | Blocked | Yes | +##### model + +Override which model handles the skill: + +```yaml +--- +name: quick-lint +description: Fast code linting checks... +model: haiku +--- +``` + +**Values:** `sonnet`, `opus`, `haiku`, `inherit` (default), or a full model ID (e.g., `claude-sonnet-4-5-20250929`) + +Use `haiku` for fast/cheap skills, `opus` for complex reasoning requiring maximum capability. Default behavior (`inherit`) uses the conversation's current model. + +See `references/advanced-frontmatter.md` for detailed guidance on model selection. + +##### hooks + +Define scoped hooks that activate only when this skill is in use: + +```yaml +--- +name: secure-writer +description: Write files with validation... +hooks: + PreToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/validate-write.sh" +--- +``` + +Scoped hooks follow the same event/matcher/hook structure as `hooks.json` but are lifecycle-bound to the skill. Supported events: `PreToolUse`, `PostToolUse`, `Stop`. + +See `references/advanced-frontmatter.md` for full syntax and comparison with `hooks.json`. + #### Bundled Resources (optional) ##### Scripts (`scripts/`) @@ -263,6 +302,8 @@ Skills use a three-level loading system to manage context efficiently: \*Unlimited because scripts can be executed without reading into context window. +**Visibility budget:** Claude Code allocates a character budget (default ~15,000 chars via `SLASH_COMMAND_TOOL_CHAR_BUDGET`) for skill descriptions. When total description text across all installed skills exceeds this budget, some skills may be excluded from auto-discovery. Keep descriptions concise and move detail into the SKILL.md body and references. See `references/advanced-frontmatter.md` for optimization guidance. + ## Skill Creation Process To create a skill, follow these six steps. For detailed instructions on each step, see `references/skill-creation-workflow.md`. @@ -369,6 +410,8 @@ Before finalizing a skill: - [ ] (Optional) `skills` array if loading other skills (requires `context: fork`) - [ ] (Optional) `user-invocable` field if hiding from slash menu - [ ] (Optional) `disable-model-invocation` field if blocking programmatic use +- [ ] (Optional) `model` field if overriding model (`sonnet`/`opus`/`haiku`/`inherit`) +- [ ] (Optional) `hooks` field for scoped hooks (same format as `hooks.json`) - [ ] Markdown body is present and substantial - [ ] Referenced files actually exist diff --git a/plugins/plugin-dev/skills/skill-development/references/advanced-frontmatter.md b/plugins/plugin-dev/skills/skill-development/references/advanced-frontmatter.md new file mode 100644 index 0000000..7a045c9 --- /dev/null +++ b/plugins/plugin-dev/skills/skill-development/references/advanced-frontmatter.md @@ -0,0 +1,162 @@ +# Advanced Skill Frontmatter Fields + +This reference covers frontmatter fields that go beyond the core `name` and `description` requirements. These fields enable model selection, scoped hooks, and context budget optimization. + +## model + +Override the model used when a skill is active. + +### Values + +| Value | Behavior | +| ------------- | ----------------------------------------------------- | +| `inherit` | Use the conversation's current model (default) | +| `sonnet` | Claude Sonnet — balanced performance and cost | +| `opus` | Claude Opus — maximum capability, highest cost | +| `haiku` | Claude Haiku — fastest, lowest cost | +| Full model ID | Specific version (e.g., `claude-sonnet-4-5-20250929`) | + +### When to Use Each + +- **`inherit` (default):** Most skills. Lets the user's model choice apply. +- **`haiku`:** Fast, cost-sensitive operations — linting, formatting checks, simple lookups. Good for skills that run frequently. +- **`sonnet`:** Standard workflows — code review, generation, analysis. The balanced default. +- **`opus`:** Complex reasoning — architectural decisions, security audits, detailed analysis requiring maximum capability. +- **Full model ID:** Pin to a specific version when skill behavior depends on exact model capabilities. + +### Example + +```yaml +--- +name: quick-lint +description: This skill should be used for fast code quality checks... +model: haiku +--- +``` + +### Notes + +- Shorthand names (`sonnet`, `opus`, `haiku`) resolve to the current default version of each family +- The `model` field is shared with commands (same syntax and behavior) +- When `context: fork` is set, the model applies to the forked subagent + +## hooks (Scoped Hooks) + +Define hooks that activate only when the skill is in use, rather than globally for all tool calls. + +### Concept + +Unlike `hooks.json` (which applies globally whenever the plugin is active), scoped hooks in frontmatter are lifecycle-bound to the skill. They activate when the skill loads and deactivate when it completes. This enables skill-specific validation without affecting other workflows. + +### Format + +The `hooks` field uses the same event/matcher/hook structure as `hooks.json`: + +```yaml +--- +name: validated-writer +description: Write files with safety validation... +hooks: + PreToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/validate-write.sh" + timeout: 10 + PostToolUse: + - matcher: Write + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/post-write-check.sh" +--- +``` + +### Supported Events + +Scoped hooks support a subset of hook events: + +| Event | Purpose | +| ------------- | ------------------------------------------------ | +| `PreToolUse` | Validate or block tool calls before execution | +| `PostToolUse` | Run checks after successful tool execution | +| `Stop` | Verify completion criteria before skill finishes | + +Other events (`SessionStart`, `UserPromptSubmit`, etc.) are session-level and don't apply to skill scope. + +### Comparison with hooks.json + +| Aspect | `hooks.json` | Frontmatter `hooks` | +| -------- | ------------------------------------------ | --------------------------------------------- | +| Scope | Global (always active when plugin enabled) | Skill-specific (active only during skill use) | +| Events | All 11+ hook events | PreToolUse, PostToolUse, Stop | +| Location | `hooks/hooks.json` file | YAML frontmatter in SKILL.md | +| Use case | Plugin-wide validation, logging | Skill-specific safety checks | + +### Use Cases + +- **Skill-specific validation:** A "database writer" skill that validates SQL before execution +- **Restricted workflows:** A "deploy" skill that checks branch and test status before allowing Bash commands +- **Quality gates:** A "code generator" skill that runs linting after every Write operation + +### Hook Types in Frontmatter + +Both `command` and `prompt` hook types work in frontmatter: + +**Command hook** (executes a script): + +```yaml +hooks: + PreToolUse: + - matcher: Bash + hooks: + - type: command + command: "${CLAUDE_PLUGIN_ROOT}/scripts/check-safety.sh" +``` + +**Prompt hook** (LLM evaluation — for Stop events): + +```yaml +hooks: + Stop: + - hooks: + - type: prompt + prompt: 'Verify that all generated code has tests. Return {"decision": "stop"} if satisfied or {"decision": "continue", "reason": "missing tests for..."} if not.' +``` + +## Skill Visibility Budget + +Claude Code allocates a character budget for skill descriptions to manage context window usage efficiently. + +### How It Works + +1. All installed skills contribute their `description` text to a shared budget +2. Default budget: ~15,000 characters (controlled by `SLASH_COMMAND_TOOL_CHAR_BUDGET`) +3. When total descriptions exceed the budget, lower-priority skills may be excluded from auto-discovery +4. Excluded skills are still available via explicit `/skill-name` invocation — they just won't auto-trigger + +### What Counts Against the Budget + +- The `description` frontmatter field text +- Skill name and metadata overhead +- This applies across ALL installed plugins, not just yours + +### Optimization Strategies + +1. **Keep descriptions concise:** Target 100-300 characters for the description field +2. **Use trigger phrases, not explanations:** "create a hook", "add PreToolUse" is better than "This skill provides comprehensive guidance for creating event-driven automation..." +3. **Move detail to SKILL.md body:** The body only loads when the skill triggers, not at discovery time +4. **Progressive disclosure:** Description (always loaded) → SKILL.md body (on trigger) → references (on demand) + +### Checking Budget Usage + +- `/context` command shows context usage including excluded skills if over budget +- Environment variable: `SLASH_COMMAND_TOOL_CHAR_BUDGET=20000` to increase budget +- Monitor with: `claude --debug` shows skill loading details + +### Practical Impact + +For most plugins with 5-15 skills, the default budget is sufficient. Budget becomes a concern when: + +- Multiple plugins are installed simultaneously (each adding descriptions) +- Individual skill descriptions exceed 500 characters +- A plugin has 20+ skills with verbose descriptions