# CodeBuddy Code Skills (Skills System)

Skills are CodeBuddy Code's extension capability system that allows you to create specialized domain knowledge and workflow templates, enabling the AI assistant to handle specific types of tasks with greater expertise.

## What are Skills

Skills are like "professional training" for the AI assistant. With Skills, you can:

- **Encapsulate specialized knowledge**: Package domain-specific best practices and operational procedures into reusable capabilities
- **Provide workflow templates**: Define standardized task processing flows to improve work efficiency
- **Extend AI capabilities**: Enable the AI assistant to handle more specialized and complex tasks
- **Share team collaboration**: Project-level Skills allow teams to share specialized knowledge among members

## Skills vs Slash Commands

| Feature | Skills | Slash Commands |
|-----|--------|----------------|
| **Invocation** | Automatically identified and invoked by the AI model | Manually entered by the user |
| **Use Case** | Specialized domain task processing | Quick operations and workflows |
| **Permission Control** | Supports tool allowlist restrictions | No special permission control |
| **Working Directory** | Supports custom base directory | Uses current working directory |
| **Visibility** | Transparent to user, AI makes decisions automatically | Actively initiated by user |

**In simple terms**:
- **Slash Commands** are shortcuts actively invoked by users
- **Skills** are specialized capabilities automatically selected by the AI based on task requirements

## Creating Skills

### Directory Structure

Skills are defined by creating a `SKILL.md` file in specific directories:

1. **Project-level Skills**: `.codebuddy/skills/` (in project root)
2. **User-level Skills**: `~/.codebuddy/skills/` (in user home directory)

Each Skill has its own directory containing a `SKILL.md` file:

```
.codebuddy/skills/
├── pdf/
│   └── SKILL.md
├── data-analysis/
│   └── SKILL.md
└── code-review/
    └── SKILL.md
```

### SKILL.md Format

Skill files use Markdown format and support YAML Frontmatter for defining metadata:

```markdown

You are a PDF document processing expert, skilled in:
- Parsing and extracting PDF content
- Converting PDFs to other formats
- Generating PDF reports

When users need to handle PDF-related tasks, use the following workflow:
1. First check if the PDF file exists
2. Use appropriate tools to extract content
3. Process according to requirements
4. Generate result reports

Available tools:
- pdftotext: Extract text content
- pdfinfo: Get PDF information
```

### Frontmatter Fields

| Field | Required | Description | Example |
|-----|------|------|------|
| `name` | No | Skill name, uses directory name if not specified | `pdf` |
| `description` | No | Skill description, helps AI understand when to use it | `PDF document processing expert (project)` |
| `allowed-tools` | No | Allowlist of permitted tools, comma-separated | `Read, Write, Bash` |
| `disable-model-invocation` | No | When set to `true`, the Skill will not appear in the Skill tool and can only be triggered manually via `/skill-name` | `true` |
| `user-invocable` | No | When set to `false`, the Skill is hidden from the `/` menu and is only available for internal AI invocation or reference by other Skills, defaults to `true` | `false` |
| `context` | No | When set to `fork`, the Skill executes in an isolated subagent context | `fork` |
| `agent` | No | Specifies the subagent type, only effective when `context: fork` | `Explore` |
| `model` | No | Specifies the model used when the Skill executes (only effective when `context: fork`; falls back to the agent's default model when not configured) | `claude-sonnet-4` |
| `hooks` | No | Declares Skill-specific hooks in SKILL.md. Only effective when `context: fork`. See [Configuring Hooks in a Skill](#configuring-hooks-in-a-skill) | See below |

## Variable Placeholders

The content of SKILL.md supports the following placeholders, which are automatically substituted at load or execution time. The same placeholders also apply to custom slash commands and subagent definitions.

| Placeholder | Replaced With | Applicable Sources |
|------|------|------|
| `${CODEBUDDY_PLUGIN_ROOT}` | Plugin installation root directory | Plugin-sourced skills only |
| `${CODEBUDDY_SKILL_DIR}` | Absolute path of the directory containing the current SKILL.md | All sources |
| `${CODEBUDDY_SESSION_ID}` | Current session ID (injected at runtime) | All sources |
| `${MY_ENV_VAR}` and other uppercase environment variables | The value of `process.env.MY_ENV_VAR` | All sources |
| `${MY_ENV_VAR:-default}` | The environment variable, or the default value when missing | All sources |

For compatibility with Claude Code, `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_SKILL_DIR}`, and `${CLAUDE_SESSION_ID}` are also recognized as equivalent aliases.

Unset environment variable placeholders are left as-is rather than replaced with an empty string; in user- or project-sourced skills, `${CODEBUDDY_PLUGIN_ROOT}` is preserved literally (this variable applies only to plugin sources).

**Example**:

```markdown
---
description: Skill example with placeholders
---

Read the script @${CODEBUDDY_SKILL_DIR}/scripts/analyze.py and execute it using the secret ${MY_API_TOKEN:-dev-fallback}.
Current session identifier: ${CODEBUDDY_SESSION_ID}
```

## Execute Shell Commands

Like [Slash Commands](slash-commands.md), Skills also support inline Shell command execution in SKILL.md using the `` !`command` `` syntax. When a Skill is triggered (whether automatically by AI or manually by the user via `/skill-name`), these commands are executed and their output replaces the command in the Skill content for subsequent AI analysis.

**Example**:

```markdown
---
description: Project status analysis
---

### Current Working Directory

!`echo "CWD=$(pwd)"`

### Git Status

!`git status --short`

### Recent Commits

!`git log --oneline -5`

Please analyze the current project status based on the above information.
```

### Supported Features

- **`$ARGUMENTS` parameter substitution**: Before Shell command execution, `$ARGUMENTS` is replaced with the arguments passed by the user
- **`@file` file references**: After Shell command execution, `@file` references are processed and file content is injected
- **Error isolation**: A single command failure does not affect other commands; failed commands are replaced with empty strings

> 💡 **Processing pipeline**: `$ARGUMENTS` substitution → `` !`command` `` execution → `@file` reference processing, consistent with the processing order of Slash Commands.

## Context Fork

`context: fork` makes the Skill run in an isolated subagent context without accessing conversation history.

```yaml
---
name: deep-research
description: Deep research on a topic
context: fork
agent: Explore
---

Research $ARGUMENTS:
1. Use Glob and Grep to find relevant files
2. Read and analyze code
3. Summarize findings with specific file references
```

### Available Agent Types

| Type | Description |
|-----|------|
| `general-purpose` | General purpose (default) |
| `Explore` | Read-only tools, optimized for codebase exploration |
| `Plan` | Planning and analysis |
| Custom | Agents defined in `.codebuddy/agents/` |

### Hidden Skills (user-invocable)

`user-invocable: false` hides the Skill from the `/` menu, suitable for:
- Background knowledge Skills (e.g., project specifications, coding standards)
- Helper Skills only referenced by other Skills or internal AI invocation

```yaml
---
name: project-guidelines
description: Project coding standards and best practices
user-invocable: false
---

# Project Coding Standards

This project follows the following coding standards:
- Use TypeScript strict mode
- Function naming uses camelCase
- Component naming uses PascalCase
...
```

Such Skills are loaded into the AI's context but cannot be directly invoked by users through the `/` menu.

### Execution Flow

1. Create a new isolated context
2. The subagent receives the Skill content as a prompt
3. The `agent` field determines the execution environment
4. Results are returned to the main conversation

> **Note**: `context: fork` is only suitable for Skills that contain specific tasks. Skills with only guidelines and no concrete tasks will not produce meaningful output.

## Configuring Hooks in a Skill

> **Version requirement**: The Skill frontmatter `hooks` field requires a version of CodeBuddy Code that supports Frontmatter Hooks (Beta).

In addition to globally configuring hooks in `~/.codebuddy/settings.json`, a Skill can also declare a `hooks` field directly in the SKILL.md frontmatter, packaging the hook together with the Skill itself. This is especially useful for fork-style Skills — you can add guards, logs, and callbacks inside the fork subagent without polluting the main session.

### Applicability

- **Only effective when `context: fork`**: Skills using the injection path (the default inline mode) do not have clear lifecycle boundaries; frontmatter hooks will be parsed but not registered with the runtime.
- **Lifecycle bound to the fork subagent**: Hooks are registered when the fork subagent starts and automatically cleaned up when it ends, without affecting the main session or other Skills.
- **`Stop` is automatically converted to `SubagentStop`**: Writing the `Stop` event in frontmatter is automatically rewritten to `SubagentStop` to align with the actual event of subagent completion.

### Field Format

The structure of the `hooks` field is identical to `hooks` in `settings.json` — grouped by event name, with each entry supporting a `matcher` and a `hooks[]` array:

```yaml
---
name: secure-reviewer
description: Code review Skill that checks file allowlist before execution
context: fork
agent: Explore
hooks:
  PreToolUse:
    - matcher: "Read|Glob|Grep"
      hooks:
        - type: command
          command: ${CODEBUDDY_SKILL_DIR}/scripts/check-paths.sh
          timeout: 10
  PostToolUse:
    - matcher: "Bash"
      hooks:
        - type: prompt
          prompt: "Check whether the Bash output contains sensitive information; if so, explain it in the reason field."
  Stop:  # Automatically rewritten to SubagentStop
    - hooks:
        - type: command
          command: echo "review skill finished" >> ${CODEBUDDY_PROJECT_DIR}/.cbc-review.log
---

Please review the files mentioned in $ARGUMENTS...
```

Supported hook `type`s:

- `command`: Executes a Shell command (with optional fields like `shell: bash | powershell`, `timeout`, `if`, `once`, `async`)
- `prompt`: Hands off to a small model (default Haiku-class) for semantic decisions
- `agent`: Spins up a subagent for more complex decisions, with optional `agentType` / `model`
- `http`: Sends the event payload via POST/PUT/PATCH to the specified URL

For complete field semantics, see the [Hook Reference Guide](./hooks.md).

### Security Gate: admin-trusted

For security reasons, **frontmatter hooks from Skills sourced from non-built-in origins are not registered by default**. Currently, all Skills loaded from `.codebuddy/skills/`, project-local sources, or plugin marketplaces are considered "untrusted sources" — they can silently trigger Shell commands, so explicit user consent is required.

To enable, set the following in `~/.codebuddy/settings.json`:

```json
{
  "allowUntrustedFrontmatterHooks": true
}
```

Once enabled, frontmatter hooks from Skills/Agents of all sources will be registered; otherwise, the CLI will print a warning like the following and skip the Skill's hooks:

```
[AgentTask] Frontmatter hooks from skill 'secure-reviewer' skipped
(source not admin-trusted; enable `allowUntrustedFrontmatterHooks` in settings to allow)
```

> Built-in product-bundled Skills are not subject to this gate and are automatically allowed. Hooks configured by plugins via `hooks/hooks.json` go through a different path and are **not** controlled by this gate.

### Merging with Global Hooks

Skill frontmatter hooks and global hooks in `settings.json` are in an **additive merge** relationship — for the same event, all matching hooks from both sides are triggered in parallel; there is no override. The differences are:

| Source | Scope | Subject to admin-trusted gate |
| --- | --- | --- |
| `settings.json` (global/project/local) | Entire session | No |
| Plugin `hooks/hooks.json` | Entire session (when plugin is enabled) | No |
| Agent `.md` frontmatter | The subagent's lifecycle | Yes |
| Skill `SKILL.md` frontmatter (fork only) | The fork subagent's lifecycle | Yes |

### Debugging

- Set `CODEBUDDY_DEBUG=1` at startup to see registration lines like `[ScopedHookRegistry] registered N hook config(s) for scope ...` in the logs.
- Invalid hook definitions in the frontmatter are silently dropped, but a `[parseFrontmatterHooks] skill 'xxx': event 'YYY' invalid: ...` message is emitted in the log — check the logs to locate issues.

## Usage Examples

### Example 1: PDF Processing Skill

**File**: `.codebuddy/skills/pdf/SKILL.md`

```markdown
---
name: pdf
description: PDF document processing and conversion expert
allowed-tools: Read, Write, Bash, WebFetch
---

# PDF Processing Expert

You are a professional PDF document processing expert.

## Core Capabilities
- Extract PDF text content
- Convert PDFs to Markdown, HTML and other formats
- Merge and split PDF files
- Extract PDF metadata and bookmarks

## Workflow
1. Check if the PDF file exists and is accessible
2. Use pdftotext or pdfinfo to get basic information
3. Select appropriate processing tools based on task type
4. Validate completeness of output results

## Available Tools
- pdftotext: Extract plain text
- pdfinfo: Get document information
- pdftk: Merge and split operations
```

**Usage**: When a user asks "Help me extract the content from this PDF", the AI will automatically recognize the need for PDF processing capabilities and invoke this Skill.

### Example 2: Data Analysis Skill

**File**: `~/.codebuddy/skills/data-analysis/SKILL.md`

```markdown
---
name: data-analysis
description: Data analysis and visualization expert
allowed-tools: Read, Write, Bash, WebFetch, NotebookEdit
---

# Data Analysis Expert

You are a professional data analyst skilled in using Python and related tools for data analysis.

## Core Capabilities
- Data cleaning and preprocessing
- Statistical analysis and modeling
- Data visualization
- Generate analysis reports

## Analysis Workflow
1. Understand data structure and quality
2. Clean and preprocess data
3. Perform statistical analysis
4. Create visualization charts
5. Generate analytical conclusions

## Toolset
- pandas: Data processing
- numpy: Numerical computation
- matplotlib/seaborn: Visualization
- scikit-learn: Machine learning

## Best Practices
- Always explore data quality first
- Use Jupyter Notebook for interactive analysis
- Save intermediate results to avoid redundant computation
```

### Example 3: Code Review Skill

**File**: `.codebuddy/skills/code-review/SKILL.md`

```markdown
---
name: code-review
description: Code review and quality inspection expert
allowed-tools: Read, Grep, Bash, Edit
---

# Code Review Expert

You are an experienced code reviewer who follows industry best practices.

## Review Focus
1. **Code Quality**
   - Naming conventions
   - Code complexity
   - Code duplication

2. **Security**
   - SQL injection risks
   - XSS vulnerabilities
   - Authentication and authorization issues

3. **Performance**
   - Algorithm efficiency
   - Resource usage
   - Caching strategies

4. **Maintainability**
   - Code comments
   - Modular design
   - Test coverage

## Review Process
1. Understand the purpose of code changes
2. Check code style and conventions
3. Analyze potential bugs and performance issues
4. Verify security
5. Provide constructive improvement suggestions

## Output Format
- ✅ Strengths: List what was done well
- ⚠️ Issues: Point out areas needing improvement
- 💡 Suggestions: Provide specific improvement recommendations
```

## How AI Selects Skills

The AI decides whether to invoke a Skill based on the following factors:

1. **Task Matching**: Relevance between task description and Skill description
2. **Tool Requirements**: Whether required tools are within the allowed-tools scope
3. **Context Relevance**: Whether the current conversation context is suitable for using the Skill
4. **Skill Source**: Project-level Skills have priority over user-level Skills

## Permission Control

### allowed-tools Allowlist

Restrict which tools a Skill can use via the `allowed-tools` field:

```yaml
allowed-tools: Read, Write, Bash(git:*), Grep
```

Supported tool pattern matching:
- `Bash(git:*)` - Only allow git-related commands
- `Edit(src/**/*.ts)` - Only allow editing specific path files

### Working Directory Restrictions

Each Skill has its own `baseDirectory` (the directory containing SKILL.md), which can be referenced in Skill instructions:

```markdown
When processing files, prioritize searching for related resources in the {baseDirectory} directory.
```

## Best Practices

### 1. Clear Skill Description

```yaml
# ❌ Poor
description: Process files

# ✅ Good
description: PDF document parsing and conversion expert, supports text extraction and format conversion (project)
```

### 2. Detailed Instruction Content

Provide detailed:
- Core capability descriptions
- Standard workflow procedures
- Available tool lists
- Common scenario handling methods
- Output format requirements

### 3. Reasonable Tool Permissions

Only grant necessary tool permissions:

```yaml
# ❌ Excessive permissions
allowed-tools: Bash

# ✅ Precise control
allowed-tools: Read, Write, Bash(git:status,git:diff), Grep
```

### 4. Organize Skill Directories

Organize Skills by functional domains:

```
.codebuddy/skills/
├── document/
│   ├── pdf/SKILL.md
│   └── markdown/SKILL.md
├── data/
│   ├── analysis/SKILL.md
│   └── visualization/SKILL.md
└── code/
    ├── review/SKILL.md
    └── refactor/SKILL.md
```

## Debugging Skills

### View Loaded Skills

Use the `/skills` command to view all currently loaded Skills:

```
/skills
```

The Skills panel will display:
- **User skills**: User-level Skills (`~/.codebuddy/skills/`)
- **Project skills**: Project-level Skills (`.codebuddy/skills/`)
- **Plugin skills**: Skills provided by plugins

Each Skill will show its name and estimated token count.

### Common Issues

**Q: Skill not being triggered?**
- Check if description clearly describes the Skill's functionality
- Confirm task description matches Skill capabilities
- Verify allowed-tools includes required tools

**Q: Skill has insufficient permissions?**
- Check allowed-tools configuration
- Confirm tool names are spelled correctly
- Use pattern matching for precise permission control

**Q: Project-level and user-level Skill conflict?**
- Project-level Skills have higher priority
- Use different names to avoid conflicts

## Integration with Other Features

### Skills + Memory

Skills can access information stored in the Memory system:

```markdown
When performing data analysis, refer to data schemas and business rules saved in Memory.
```

### Skills + Slash Commands

Slash Commands can reference Skills:

```markdown
<!-- .codebuddy/commands/analyze-data.md -->
Please use the data-analysis skill to analyze file: $1
```

### Skills + MCP

Skills can invoke external tools provided by MCP (if included in allowed-tools).

## Next Steps

- [Slash Commands](slash-commands.md) - Learn about user-initiated commands
- [Settings Configuration](settings.md) - Configure tool permissions
- [MCP Integration](mcp.md) - Extend external tool capabilities

---

*Skills - Making AI a domain expert*
