# Plugin Development Guide

This guide covers how to create plugins, skills, hooks, and slash commands for CVC.

---

## Table of Contents

- [Plugin Structure](#plugin-structure)
- [Plugin Manifest](#plugin-manifest)
- [Slash Commands](#slash-commands)
- [Sub-Agent Definitions](#sub-agent-definitions)
- [Hook Scripts](#hook-scripts)
- [Skills](#skills)
- [Settings Management](#settings-management)
- [Distribution](#distribution)

---

## Plugin Structure

Plugins live in `.cvc/plugins/` (project-local) or `~/.cvc/plugins/` (global):

```
my-plugin/
├── .cvc-plugin/
│   └── plugin.json          # Required: plugin manifest
├── commands/
│   ├── deploy.md            # Slash command: /deploy
│   └── analyze.md           # Slash command: /analyze
├── agents/
│   └── code-reviewer.md     # Sub-agent definition
├── hooks/
│   ├── pre-tool-use.sh      # Hook: runs before tools
│   └── post-tool-use.js     # Hook: runs after tools
└── settings/
    └── managed-settings.json # Settings injected by plugin
```

CVC auto-discovers plugins by scanning for directories containing `.cvc-plugin/plugin.json`.

---

## Plugin Manifest

Every plugin requires a `.cvc-plugin/plugin.json` file:

```json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "A brief description of what this plugin does",
  "author": "Your Name",
  "homepage": "https://github.com/you/my-plugin",
  "tags": ["productivity", "code-review"],
  "requires": {
    "cvc": ">=2.0.0"
  }
}
```

### Fields

| Field | Required | Description |
|-------|----------|-------------|
| `name` | Yes | Unique plugin identifier (kebab-case) |
| `version` | Yes | Semver version string |
| `description` | No | Short description |
| `author` | No | Author name or organization |
| `homepage` | No | URL to docs or repository |
| `tags` | No | Discovery tags |
| `requires.cvc` | No | Minimum CVC version |

---

## Slash Commands

Place `.md` files in the `commands/` directory. The filename becomes the command name.

### Example: `/deploy`

```markdown
---
name: deploy
description: Deploy the current project
allowed_tools:
  - bash
  - read_file
  - write_file
---

You are a deployment assistant. Help the user deploy their project.

Steps:
1. Read the project configuration (package.json, Dockerfile, etc.)
2. Identify the deployment target
3. Run the appropriate deployment commands
4. Verify the deployment succeeded
```

### Command Frontmatter

| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Command name (overrides filename) |
| `description` | string | Shown in `/help` output |
| `allowed_tools` | string[] | Tools this command can use |

When a user types `/deploy`, CVC injects the command's markdown content into the system prompt and restricts tools to those listed in `allowed_tools`.

---

## Sub-Agent Definitions

Place `.md` files in the `agents/` directory to define reusable sub-agents:

### Example: Code Reviewer Agent

```markdown
---
name: code-reviewer
description: Reviews code changes for quality and correctness
model: claude-sonnet-4-20250514
max_iterations: 10
allowed_tools:
  - read_file
  - grep_search
  - glob_search
---

You are a senior code reviewer. Analyze the provided code changes and produce a review.

## Review Criteria

1. **Correctness**: Does the code do what it claims?
2. **Security**: Any vulnerabilities (OWASP Top 10)?
3. **Performance**: Any obvious bottlenecks?
4. **Style**: Does it follow project conventions?

## Output Format

Produce a structured review with:
- Summary (1-2 sentences)
- Issues found (severity: critical/warning/info)
- Suggestions for improvement
```

### Agent Frontmatter

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `name` | string | filename | Agent identifier |
| `description` | string | — | Purpose description |
| `model` | string | parent model | LLM model to use |
| `max_iterations` | number | 15 | Max tool-use loops |
| `allowed_tools` | string[] | read-only set | Available tools |

Sub-agents are invoked via the `sub_agent` tool in conversations:

```
> Use the code-reviewer agent to review my last commit
```

---

## Hook Scripts

Hooks are scripts that run at specific points in the agent lifecycle. They can be shell scripts (`.sh`) or JavaScript (`.js`).

### Supported Events

| Event | Filename | When |
|-------|----------|------|
| `PreToolUse` | `pre-tool-use.{sh,js}` | Before a tool executes |
| `PostToolUse` | `post-tool-use.{sh,js}` | After a tool completes |
| `SessionStart` | `session-start.{sh,js}` | Agent session begins |
| `SessionStop` | `session-stop.{sh,js}` | Agent session ends |
| `Stop` | `stop.{sh,js}` | Agent tries to end its turn |
| `SubagentStop` | `subagent-stop.{sh,js}` | Sub-agent completes |
| `UserPromptSubmit` | `user-prompt-submit.{sh,js}` | User submits a prompt |
| `PreCompact` | `pre-compact.{sh,js}` | Before context is compressed |
| `Notification` | `notification.{sh,js}` | Custom notification |

### Exit Code Semantics

| Exit Code | Meaning |
|-----------|---------|
| `0` | Proceed — allow the action |
| `1` | Ask — prompt user for confirmation |
| `2` | Block — prevent the action entirely |

### Shell Hook Example

```bash
#!/bin/bash
# hooks/pre-tool-use.sh
# Block write operations to production config files

# Input arrives as JSON on stdin
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name')
FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty')

if [[ "$TOOL" == "write_file" && "$FILE" == *"production"* ]]; then
    echo '{"reason": "Cannot modify production config files"}'
    exit 2  # Block
fi

exit 0  # Proceed
```

### JavaScript Hook Example

```javascript
// hooks/post-tool-use.js
// Log all file modifications to an audit file

const input = JSON.parse(await Bun.stdin.text());

if (input.tool_name === "write_file" || input.tool_name === "edit_file") {
    const entry = {
        timestamp: new Date().toISOString(),
        tool: input.tool_name,
        file: input.input.file_path,
        user: process.env.USER,
    };
    const log = Bun.file(".cvc/file-audit.jsonl");
    await Bun.write(log, (await log.text().catch(() => "")) + JSON.stringify(entry) + "\n");
}

process.exit(0);
```

### Hook Input Payload

Hooks receive a JSON payload on stdin:

**PreToolUse:**
```json
{
    "event": "PreToolUse",
    "tool_name": "write_file",
    "input": {
        "file_path": "/path/to/file.ts",
        "content": "..."
    },
    "session_id": "abc123",
    "branch": "main"
}
```

**PostToolUse:**
```json
{
    "event": "PostToolUse",
    "tool_name": "write_file",
    "input": { "..." },
    "output": { "success": true },
    "duration_ms": 42,
    "session_id": "abc123"
}
```

### Hook Search Order

1. `.cvc/hooks/` (project-local)
2. Plugin `hooks/` directories (in plugin load order)
3. `~/.cvc/hooks/` (global)

All matching hooks run in this order. The most restrictive exit code wins (2 > 1 > 0).

---

## Skills

Skills are auto-invoked prompt extensions. Place `.md` files in `.cvc/skills/` or `~/.cvc/skills/`.

### Example: Security Audit Skill

```markdown
---
name: security-audit
description: Automated security analysis
auto_invoke:
  - "security.*audit"
  - "check.*vulnerabilities"
  - "scan.*security"
tools:
  - read_file
  - grep_search
  - glob_search
  - bash
---

You are a security auditor. When this skill is activated, perform a comprehensive security review:

## Checks

1. **Dependencies**: Check for known vulnerabilities in package.json / requirements.txt
2. **Secrets**: Scan for hardcoded API keys, passwords, or tokens
3. **Injection**: Look for SQL injection, XSS, and command injection vectors
4. **Auth**: Review authentication and authorization patterns
5. **Crypto**: Check for weak cryptographic practices

## Output

Produce a security report with:
- Risk level (Critical / High / Medium / Low)
- Findings with file locations
- Remediation recommendations
```

### Skill Frontmatter

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Skill identifier |
| `description` | string | Yes | Shown when listing skills |
| `auto_invoke` | string[] | No | Regex patterns matched against user prompts |
| `tools` | string[] | No | Tools available when skill is active |
| `priority` | number | No | Order when multiple skills match (lower = first) |

### How Skills Work

1. User submits a prompt
2. CVC matches the prompt against all skill `auto_invoke` patterns
3. Matching skills' markdown content is injected into the system prompt
4. Tool restrictions from the skill are applied
5. The LLM responds with the skill's instructions in context

Skills can also be manually invoked: `/skill security-audit`.

---

## Settings Management

Plugins can inject settings into the CVC configuration:

### `settings/managed-settings.json`

```json
{
    "auto_commit_interval": 3,
    "compact_threshold": 0.8,
    "tools": {
        "bash": {
            "require_confirmation": true
        }
    },
    "hooks": {
        "pre_tool_use": {
            "timeout_ms": 5000
        }
    }
}
```

Plugin-managed settings have the **highest priority** in the settings hierarchy:

```
Plugin managed-settings.json  (highest)
.cvc/managed-settings.json
.cvc/settings.json
.cvc/settings.local.json
~/.cvc/settings.json           (lowest)
```

---

## Distribution

### Directory Distribution

The simplest method — share the plugin directory:

```bash
# Install from a Git repo
git clone https://github.com/you/my-plugin.git .cvc/plugins/my-plugin

# Or copy globally
cp -r my-plugin ~/.cvc/plugins/
```

### Plugin Discovery

CVC scans these directories for plugins:

1. `.cvc/plugins/` — project-local plugins
2. `~/.cvc/plugins/` — global plugins

Each subdirectory containing `.cvc-plugin/plugin.json` is loaded as a plugin.

### Testing Your Plugin

```bash
# Create a test project
mkdir /tmp/test-project && cd /tmp/test-project
cvc init

# Symlink your plugin for development
ln -s /path/to/your/my-plugin .cvc/plugins/my-plugin

# Start the agent and test
cvc agent
> /help                    # Should show your custom commands
> /your-command            # Test slash commands
> Use the your-agent agent  # Test sub-agents
```

---

## Examples

### Minimal Plugin (Single Command)

```
hello-plugin/
├── .cvc-plugin/
│   └── plugin.json
└── commands/
    └── hello.md
```

**plugin.json:**
```json
{"name": "hello", "version": "1.0.0"}
```

**commands/hello.md:**
```markdown
---
name: hello
description: Say hello
---
Respond with a friendly greeting and a fun fact about the user's project.
```

### Full-Featured Plugin

See the reference plugins in `_claude_code_ref/plugins/` for complete examples:
- `code-review/` — Code review automation
- `security-guidance/` — Security analysis
- `feature-dev/` — Feature development workflow
- `hookify/` — Hook management
