Skill: drumrobot/claudify (version 0.1.2)

--- name: claudify metadata: author: es6kr version: "0.1.2" depends-on: [skill-kit] description: Convert functionality into Claude Code automation. Includes interactive supervisor agent pattern (see resources/agent-templates.md §7). Use when the user says "agentify", "agentic", "automate this", "create an agent", "make a plugin", "make a skill", "interactive agent", "supervisor pattern", or wants to automate a workflow as an agent, skill, or plugin. allowed-tools: - Read - Write - Edit - Glob - Skill - Bash(mkdir:*) --- # Claudify Guide users to convert functionality into the appropriate Claude Code automation type (Agent, Skill, Rule, Command, or Hook). ## Decision Matrix | Type | When to use | Implementation | | ---- | ----------- | -------------- | | **Agent** | High autonomy, multi-tool | `.claude/agents/name.md` | | **Skill** | Domain expertise, logic | `.claude/skills/name/SKILL.md` | | **Rule** | Constraints, styling | `.claude/rules/name.md` | | **Slash Command** | User types `/cmd` | Simple prompt templates | | **Hook** | Events (tool use, etc) | Automation on actions | Full comparison: [automation-decision-guide.md](./resources/automation-decision-guide.md) ## Workflow ### Step 1: Identify Candidates **If no target specified** ("agentify" alone): - Review conversation for automation candidates - Look for: verbose outputs, multi-step workflows, repeated patterns - **MUST use `multiSelect: true`** when presenting candidates (users often want multiple) **If target specified**: 1. Check local marketplaces first: - `~/.claude/plugins/marketplaces/*/plugins/*/` - Use `/skill-dedup` command to find overlaps 2. If not found locally, search remote: `WebFetch https://claudemarketplaces.com/?search=[keyword]` 3. If found, recommend existing or extend. If not, proceed to create ### Step 1.5: Merge logic / Grouping / AskUserQuestion When duplicate or similar automation candidates are found, confirm grouping and merge options with the user using AskUserQuestion. **Grouping criteria:** - Similarity in model or functionality - Contextual similarity - Keyword grouping (e.g., "openclaw management") **Merge criteria:** | Condition | Recommendation | | --------- | -------------- | | 3+ similar topics | **multi-topic Skill** | | Different triggers + same skill | General Agent | | Simple instructions + Bash script | **Skill** (Agent with skill) | | Complex multi-step + multiple tools | Agent | **AskUserQuestion (merge options):** "Candidates found. How should I structure them?" options: - "Merge related topics into one multi-topic skill (e.g., openclaw: exec/gateway/test)" - "Create separate agents for each functionality" - "Skill + Agent combination (instruction=skill, implementation=agent)" **PROHIBITED**: Do not create separate agents without merging candidates into a logical structure if they are related. ### Step 2: Gather Requirements Use AskUserQuestion to clarify: - **Triggers**: Commands or conditions that activate the automation - **Tools**: Required tools or skills - **Scope**: Global (`~/.claude/`) / Project (`.claude/`) - **Language**: code comments, variable names, documentation Question patterns: [askuserquestion-patterns.md](./resources/askuserquestion-patterns.md) ### Step 3: Recommend Type Use the [automation-decision-guide.md](./resources/automation-decision-guide.md) to recommend the best type. ### Step 4: Create **CRITICAL**: Follow the creation method for each type **Skill with scripts** (If scripts are required, use skill directory structure): ``` skill-name/ ├── SKILL.md # frontmatter + documentation + node scripts/xxx.js (mode) ├── topic-a.md # topic file ├── topic-b.md # topic file └── scripts/ └── xxx.js # actual logic (temp location, permanent storage) ``` - Do not create `tmp_*.js` in current directory; move to `scripts/` - Call in SKILL.md: `node <skill-dir>/scripts/xxx.js <mode>` - Use relative path from `__dirname` in scripts - **Separate implementation logic and topic files** **Skill (no scripts)**: **MUST** use skill-writer (do NOT create directly) ``` Skill tool: skill: "project-automation:skill-writer" ``` **Agent**: Create in `~/.claude/agents/` or `.claude/agents/` - [agent-templates.md](./resources/agent-templates.md) **Rules**: Create in `~/.claude/rules/` or `.claude/rules/` - [rules-guide.md](./resources/rules-guide.md) **Slash Command**: Create in `~/.claude/commands/` or `.claude/commands/` - [slash-command-syntax.md](./resources/slash-command-syntax.md) **Hook**: Add to settings.json - [hook-examples.md](./resources/hook-examples.md) **Plugin** (open source): - [plugin-creation.md](./resources/plugin-creation.md) ### Step 5: Validate 1. Register or copy to target location 2. Reload Claude Code: 1. Manual sync to cache, OR 2. New session to reload **Auto-sync hook**: `plugin-cache-sync.sh` syncs marketplace to cache on Edit/Write ## Output Guidelines Keep responses concise: 1. List identified candidates (with multiSelect) 2. Summarize the recommended structure (Merge logic) 3. Provide the creation plan | Context | multiSelect | | ------- | ----------- | | Automation candidates | **true** (users often want multiple) | | **Merge options** (Complexity) | **false** (merge vs separation - mutually exclusive) | | Type selection | false (mutually exclusive) | | Scope selection | false (one location) | | Feature selection | **true** (additive choices) | ## Success Case **Scenario (2026-03-09)**: - Found 3 openclaw-related functions - Proposed 3 options for merging - Result: Implementation success, user satisfied **Key factors**: 1. Identification of 3 functions 2. "Merge?" AskUserQuestion 3. merging skills using skill-writer (multi-topic) ## Ralph Mode (AskUserQuestion bypass) If `.ralph/` directory exists, operate in Ralph Mode. **Workflow Change**: | Step | User Interaction | Workflow | | ---- | ---------------- | -------- | | Step 1: Auto-detect | AskUserQuestion (multiSelect) | Summary info to `.ralph/improvements.md` | | Step 1.5: Merge logic / Structure | - | improvements.md recording | | Step 2: Requirements | AskUserQuestion | trigger/scope recommendation to improvements.md | | Step 3: Type recommendation | Recommend only | improvements.md recording | | Step 4: Implementation | Direct action | **PROHIBITED** - Use `[NEEDS_REVIEW]` tag | | Step 5: Validation | Validation | **Auto validation** (after changes are complete) | **improvements.md recording example** ```markdown ## Agentify Candidate (Implementation) ### [Candidate Name] - **Context**: [Why it was found] - **Recommended Type**: [Skill/Agent/Hook/Slash Command] - **Recommended Structure**: [Topics] - **Rationale**: [Why it's recommended] - **Tag**: [NEEDS_REVIEW] ``` ## Self-Improvement After changes are complete, **Self-improve based on conversation**: 1. Identify failure and workaround patterns 2. If candidates found, run `/skill-kit upgrade agentify`

path: resources/agent-templates.md
content: # Agent Templates

Claude Code agent templates and usage examples.

## Basic Structure

```markdown
---
name: agent-name
description: Brief description. Use when [trigger conditions].
tools: [Tool1, Tool2, Tool3]
---

# Agent Name

## Purpose

What this agent does

## Instructions

1. Step one
2. Step two
3. Step three

## Output

What to return to the parent agent
```

## Frontmatter Fields

| Field         | Required | Description                                                    |
| ------------- | -------- | -------------------------------------------------------------- |
| `name`        | ✅       | Agent identifier (kebab-case)                                  |
| `description` | ✅       | Description + trigger conditions + examples (escaped newlines) |
| `tools`       | ❌       | Allowed tools list (all if omitted)                            |
| `model`       | ❌       | Model to use (sonnet, opus, haiku)                             |

### CRITICAL: Description Field Format

The `description` field **MUST be a single line** with escaped newlines (`\n`). Multi-line descriptions break YAML parsing.

**✅ Correct (single line with `\n`):**

```yaml
description: Brief description. Use when [trigger].\n\nExamples:\n\n<example>\nContext: ...\nuser: "..."\nassistant: "..."\n</example>
```

**❌ Wrong (multi-line with `Examples:`):**

```yaml
description: Brief description.

Examples:

<example>
...
</example>
```

**✅ Correct (multi-line with `|`):**

```yaml
description: |
  Brief description
  Examples:

  <example>
  ...
  </example>
```

### Description with Examples Template

```yaml
description: [Brief description]. [Trigger keywords: "keyword1", "keyword2"]\n\nExamples:\n\n<example>\nContext: [When this triggers]\nuser: "[User message]"\nassistant: "[Agent response]"\n<Task tool call to agent-name agent>\n</example>
```

## Template Examples

### 1. Code Review Agent

```markdown
---
name: code-reviewer
description: Code review after git commits. Checks conventions against CONTRIBUTING.md if exists, otherwise offers to create one
tools: [Glob, Grep, Read, WebFetch, TodoWrite, Edit, Write, NotebookEdit]
---

# Code Reviewer

## Purpose

Review committed code for quality and convention compliance.

## Instructions

1. Check for CONTRIBUTING.md
2. If exists:
   - Check changed files (`git diff HEAD~1 --name-only`)
   - Compare with CONTRIBUTING.md rules
   - Report violations
3. If not exists:
   - Analyze project structure
   - Suggest CONTRIBUTING.md creation

## Output

- Convention violation list
- Improvement suggestions
- (If needed) CONTRIBUTING.md draft
```

### 2. CI/CD Monitor Agent

```markdown
---
name: cicd-manager
description: Check CI/CD pipeline status after git push
tools: [Bash, Read, WebFetch, TodoWrite]
---

# CI/CD Manager

## Purpose

Check and report pipeline execution status after push.

## Instructions

1. Check current branch and remote
2. Query pipeline status via API
3. If running, poll until complete (30s interval, max 10min)
4. Analyze results:
   - Success: Summary report
   - Failure: Log analysis and cause estimation
   - Not running: Check CI config

## Output

- Pipeline status (success/failed/pending)
- Cause analysis on failure
- Suggested next actions
```

### 3. Cleanup Agent

```markdown
---
name: system-cleanup
description: System cleanup and maintenance. Clean caches, temp files, and unused resources
tools: [Bash, Glob, Grep, Read, TodoWrite, Edit, Write]
---

# System Cleanup

## Purpose

Safely clean unnecessary files from the system.

## Instructions

1. Check current disk usage (`df -h`)
2. Scan cleanup targets:
   - Package caches (npm, pip, brew)
   - Build artifacts
   - Temp files
3. Calculate size for each item
4. Request user confirmation for cleanup items
5. Execute cleanup only for approved items

## Output

- Before/after size comparison
- Deleted item list
- Recovered space
```

### 4. Report Generator Agent

````markdown
---
name: report-generator
description: Generate reports from data or work history. Use for weekly reports, summaries, or analysis
tools: [Bash, Glob, Grep, Read, WebFetch, TodoWrite, Edit, Write]
---

# Report Generator

## Purpose

Collect and organize work history into reports.

## Instructions

1. Collect git commits for the period
   ```bash
   git log --since="last monday" --until="now" --oneline
   ```
````

2. Collect completed items from task tracker
3. Categorize:
   - New features
   - Bug fixes
   - Refactoring
   - Documentation
4. Write according to report template

## Output

- Report markdown
- Key achievements summary (3-5 lines)
```

### 5. Explore Agent (Fast Search)

```markdown
---
name: explore
description: Fast codebase exploration. Use for file pattern search, keyword search, structure understanding
tools: [Glob, Grep, Read, Bash]
model: haiku
---

# Explore

## Purpose
Quickly explore codebase to gather information.

## Instructions

1. Identify request type:
   - Find files → Use Glob
   - Search code → Use Grep
   - Understand structure → Use ls + tree
2. Execute search (parallel if possible)
3. Summarize results

## Output
- Found file/code locations
- Related context summary
- Additional exploration suggestions (if needed)
```

### 6. Refactor Agent

```markdown
---
name: refactor
description: Code refactoring and structure improvement. File size limits, component/utility separation
tools: [Bash, Glob, Grep, Read, Edit, Write, TodoWrite]
---

# Refactor

## Purpose

Split large files and improve structure.

## Instructions

1. Analyze target file
   - Total line count
   - Script/template/style ratio
2. Apply separation criteria:
   - Components: Consider split if >200 lines
   - Utility functions: Separate to `.ts` file
   - Types: Separate to `types.ts`
3. Present separation plan
4. Execute after approval

## Output

- Separated file list
- Changed import paths
- Items requiring verification
```

## Agent Invocation

### Using Task Tool

```
Task tool with:
- subagent_type: "agent-name"
- prompt: "Task description"
- description: "3-5 word summary"
```

### Example

```
subagent_type: "code-reviewer"
prompt: "Review the changes from the recent commit"
description: "Review recent commit"
```

### 7. Interactive Supervisor Agent (User-Decision Pattern)

Pattern for agents that collect decision items, then the **caller** presents them via AskUserQuestion for sequential resolution. The agent itself does NOT call AskUserQuestion.

```markdown
---
name: my-supervisor
description: |
  Supervisor that collects items and reports back for user decisions.
  Reports include a "Requires User Decision" section.
  The caller presents these via AskUserQuestion.

  <example>
  user: "run supervisor"
  assistant: "Launching supervisor..."
  (agent completes)
  assistant: "There are 3 items requiring user decision."
  (AskUserQuestion with the 3 items)
  </example>
skills:
  - relevant-skill
---

# My Supervisor

## Workflow
1. Phase 1: Collect data
2. Phase 2: Analyze
3. Phase 3: Report

## Final Report Format

Include a **Requires User Decision** section in the final report:

### Requires User Decision
- [ ] Item 1 — reason judgment is needed
- [ ] Item 2 — reason judgment is needed
```

**Caller Responsibility** (parent session MUST):

1. Parse "Requires User Decision" section from the agent's result
2. Present items via AskUserQuestion (multiSelect for batch selection)
3. Process selected items sequentially, asking direction per item
4. Optionally offer reassignment to sub-agents for complex items:
   ```
   AskUserQuestion: "Handle directly" / "Delegate to sub-agent" / "Skip"
   ```

**Real example**: `.claude/agents/ralph-supervisor.md`

## Best Practices

1. **Clear triggers**: Specify when to use in description
2. **Tool restrictions**: List only needed tools
3. **Step-by-step instructions**: Structure with numbers
4. **Output specification**: Define what to return
5. **Model selection**: haiku for simple tasks, opus for complex analysis


path: resources/askuserquestion-patterns.md
content: # AskUserQuestion Usage Patterns

## When to Use

1. **Decision needed** - Multiple options require selection
2. **Confirmation needed** - User consent before risky actions
3. **Next step suggestion** - Post-completion follow-up selection
4. **Ambiguous requirements** - Don't guess, ask

## Writing Rules

```typescript
AskUserQuestion({
  questions: [{
    question: "Clear and specific question?",
    header: "Short label",  // max 12 chars
    options: [
      { label: "Option name", description: "Consequence of this choice" },
      // 2-4 options, recommended first + "(Recommended)"
    ],
    multiSelect: false  // true if multiple selection needed
  }]
})
```

## Common Patterns

### Distribution Selection

```json
{
  "questions": [{
    "question": "Where should this automation be deployed?",
    "header": "Distribution",
    "options": [
      {"label": "Open Source", "description": "Publish to claudemarketplaces.com"},
      {"label": "Team/Project", "description": "Git commit, share with team"},
      {"label": "Personal (Recommended)", "description": "Save to ~/.claude/"}
    ],
    "multiSelect": false
  }]
}
```

### Trigger Selection

```json
{
  "questions": [
    {
      "question": "When should this feature run?",
      "header": "Trigger",
      "options": [
        {"label": "Automatic (context-based)", "description": "Auto-activate on specific file/keyword detection"},
        {"label": "Manual (command)", "description": "User runs /command directly"},
        {"label": "Event reaction", "description": "On file save, commit, or other events"}
      ],
      "multiSelect": false
    },
    {
      "question": "Where will you use this?",
      "header": "Scope",
      "options": [
        {"label": "All projects (Recommended)", "description": "Global install as personal workflow"},
        {"label": "This project only", "description": "For team sharing, include in Git"}
      ],
      "multiSelect": false
    }
  ]
}
```

### Type Selection

```json
{
  "questions": [{
    "question": "Which approach fits best?",
    "header": "Type Selection",
    "options": [
      {"label": "Skill", "description": "Auto-activation, instruction-based response improvement"},
      {"label": "Agent", "description": "Autonomous execution, multi-step task delegation"},
      {"label": "Hook", "description": "Event-based, automatic shell command execution"}
    ],
    "multiSelect": false
  }]
}
```

### Automation Candidates (from conversation analysis)

```json
{
  "questions": [{
    "question": "Found these automation opportunities. Which to implement?",
    "header": "Candidates",
    "options": [
      {"label": "[Pattern 1]", "description": "Brief description of what it automates"},
      {"label": "[Pattern 2]", "description": "Brief description"},
      {"label": "All of above", "description": "Create multiple automations"}
    ],
    "multiSelect": true
  }]
}
```

## Patterns to Include in Generated Automations

```markdown
## User Interaction

Use AskUserQuestion in situations requiring decisions:
- Selection between multiple approaches
- Confirmation before risky operations
- Suggest next steps after completion
```

## Avoid

- Don't proceed with guesses
- Don't list options as long text (use AskUserQuestion)
- Don't proceed with risky operations without user response


path: resources/automation-decision-guide.md
content: # Automation Decision Guide

## Automation Types Comparison

| Type | Location | Purpose | Trigger | Complexity |
|------|----------|---------|---------|------------|
| **Skill** | `.claude/skills/` | Specialized capability with instructions | Automatic (description match) | Low-Medium |
| **Agent** | `.claude/agents/` | Task delegation with specific tools | `Task` tool with `subagent_type` | Medium-High |
| **Rules** | `.claude/rules/` | AI behavior constraints, conventions | Automatic (session start) | Low |
| **Slash Command** | `.claude/commands/` | Quick prompt templates | User types `/command` | Low |
| **Hook** | `.claude/settings.json` | Lifecycle event automation | Tool use / Session events | Low-Medium |

## Decision Guide

### Choose **Skill** when

- Providing specialized instructions for a domain (PDF, Excel, API design)
- Need automatic activation based on context
- Want to guide Claude's behavior for specific file types
- Single capability that enhances Claude's responses
- **Existing shell scripts/functions** - Skill guides execution, lighter and faster than Agent

**Examples**: code-reviewer, excel-analyzer, pdf-processor

### Choose **Agent** when

- Task requires autonomous multi-step execution
- Need specific tool restrictions or permissions
- Want to delegate complex tasks to a subprocess
- Requires parallel execution or background processing

**Examples**: gitlab-cicd-manager, weekly-report-manager, macos-cleanup

### Choose **Rules** when

- Define project-wide coding conventions
- Set AI behavior constraints and guardrails
- Enforce security policies (forbidden commands, backup requirements)
- Establish documentation standards
- Need passive guidance that applies to all interactions

**Examples**: code-style.md, git-workflow.md, security-constraints.md

### Choose **Slash Command** when

- Simple prompt template or shortcut
- User-initiated action (not automatic)
- Quick access to common operations
- No complex logic needed

**Examples**: /review-pr, /summarize, /translate

### Choose **Hook** when

- React to tool use events (before/after Edit, Write, Bash, etc.)
- Automate actions on session lifecycle (start, end)
- Run shell commands in response to Claude's actions
- Need validation or side effects without user interaction

**Examples**: auto-build after file changes, lint on save, cleanup on session end

**Hook Events**: PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, SessionStart, SessionEnd, Notification, PreCompact

### Choose **Distribution Level**

| Level | Location | Target | Characteristics |
|-------|----------|--------|-----------------|
| **Open Source** | claudemarketplaces.com | All users | Universal, documentation required |
| **Team/Project** | `.claude/` (project) | Dev team | Git commit, project-specific |
| **Personal** | `~/.claude/` (global) | Self only | Experimental, personal workflow |

### Distribution Decision

| Question | Open Source | Team | Personal |
|----------|-------------|------|----------|
| Useful to other developers? | ✅ | ⚠️ | ❌ |
| Team members need this? | ⚠️ | ✅ | ❌ |
| Project-specific? | ❌ | ✅ | ⚠️ |
| Personal workflow? | ❌ | ❌ | ✅ |

## Combination Patterns

### Choose **Combination** when

Consider separation when functionality includes multiple concerns or reusable parts.

**Skill + Skill** (separation of concerns)

- Each can activate independently
- Example: `pdf-reader` + `pdf-form-filler` (read vs write)
- Example: `api-designer` + `api-validator` (design vs validation)

**Agent + Skill** (execution + guidance separation)

- Agent: Autonomous execution, tool use, background tasks
- Skill: Domain knowledge/guidelines for agent reference
- Example: `deploy-agent` (execution) + `deploy-checklist` (validation criteria)
- Example: `code-reviewer-agent` (execution) + `code-style-guide` (style rules)

**Agent + Agent** (parallel processing)

- Independent tasks that can run in parallel
- Example: `test-runner` + `lint-checker` (simultaneous execution)

### Separation Criteria Checklist

- [ ] Is each part independently useful?
- [ ] Can one change without affecting the other?
- [ ] Can it be reused in other features?
- [ ] Does separation reduce complexity?

If one is sufficient, don't separate. Over-separation increases complexity.

## Quick Reference

### File Locations

| Type | Global | Project |
|------|--------|---------|
| Skill | `~/.claude/skills/name/SKILL.md` | `.claude/skills/name/SKILL.md` |
| Agent | `~/.claude/agents/name.md` | `.claude/agents/name.md` |
| Rules | `~/.claude/rules/name.md` | `.claude/rules/name.md` |
| Command | `~/.claude/commands/name.md` | `.claude/commands/name.md` |
| Hook | `~/.claude/settings.json` | `.claude/settings.json` |

### Answer → Type Mapping

| Answer Combination | Recommended Type |
|--------------------|------------------|
| Automatic + instruction-focused | Skill |
| Automatic + tool execution | Agent |
| Automatic + constraints/conventions | Rules |
| Manual + simple | Slash Command |
| Event reaction | Hook |
| Complex requirements | Combination |


path: resources/hook-examples.md
content: # Hook Examples

Claude Code hook patterns and usage examples.

## Hook Structure

```json
{
  "hooks": {
    "<EventName>": [
      {
        "matcher": "ToolName|OtherTool",
        "hooks": [
          {
            "type": "command",
            "command": "shell-command-here"
          }
        ]
      }
    ]
  }
}
```

## Environment Variables

| Variable | Description | Available Events |
|----------|-------------|------------------|
| `CLAUDE_FILE_PATHS` | Affected file paths | PreToolUse, PostToolUse |
| `CLAUDE_TOOL_INPUT` | Tool input JSON | PreToolUse, PostToolUse |
| `CLAUDE_TOOL_OUTPUT` | Tool output | PostToolUse only |
| `CLAUDE_SESSION_ID` | Session ID | All events |

## Pattern Examples

### 1. Flag File Pattern (Deferred Execution)

Building on every file modification is slow; create a flag and process at session end.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_FILE_PATHS\" | grep -qE '\\.(ts|tsx)$'; then touch /tmp/needs-rebuild; fi"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "if [ -f /tmp/needs-rebuild ]; then rm /tmp/needs-rebuild && npm run build; fi"
          }
        ]
      }
    ]
  }
}
```

**Use cases**:
- VSCode extension build + install
- TypeScript compilation
- Docker image rebuild

### 2. Auto-Lint Pattern

Auto-format on file save.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_FILE_PATHS\" | grep -qE '\\.(js|ts|jsx|tsx)$'; then npx prettier --write \"$CLAUDE_FILE_PATHS\"; fi"
          }
        ]
      }
    ]
  }
}
```

### 3. Validation Pattern (Blocking)

Prevent dangerous operations. Return exit 1 in `PreToolUse` to block.

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT\" | grep -q 'rm -rf'; then echo 'Blocked: rm -rf not allowed' && exit 1; fi"
          }
        ]
      }
    ]
  }
}
```

### 4. Notification Pattern

Notify on completion.

```json
{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Claude session ended\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}
```

### 5. Logging Pattern

Record all tool usage.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "echo \"$(date): Tool used on $CLAUDE_FILE_PATHS\" >> ~/.claude/tool-usage.log"
          }
        ]
      }
    ]
  }
}
```

### 6. Git Auto-Stage Pattern

Auto-stage modified files.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "git add \"$CLAUDE_FILE_PATHS\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

### 7. Test Runner Pattern

Run related tests on file modification.

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_FILE_PATHS\" | grep -qE 'src/.*\\.ts$'; then npm test -- --findRelatedTests \"$CLAUDE_FILE_PATHS\"; fi"
          }
        ]
      }
    ]
  }
}
```

## Real Project Examples

### VSCode Extension Development

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_FILE_PATHS\" | grep -qE 'packages/(vscode-extension|core)/'; then touch /tmp/vsix-rebuild-needed; fi"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "if [ -f /tmp/vsix-rebuild-needed ]; then rm /tmp/vsix-rebuild-needed && pnpm build && code --install-extension *.vsix --force; fi"
          }
        ]
      }
    ]
  }
}
```

### Monorepo Build

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "PACKAGE=$(echo \"$CLAUDE_FILE_PATHS\" | grep -oE 'packages/[^/]+' | head -1); if [ -n \"$PACKAGE\" ]; then echo \"$PACKAGE\" >> /tmp/changed-packages; fi"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "if [ -f /tmp/changed-packages ]; then sort -u /tmp/changed-packages | xargs -I{} pnpm --filter {} build && rm /tmp/changed-packages; fi"
          }
        ]
      }
    ]
  }
}
```

## Matcher Limitations

**IMPORTANT**: Matcher only supports tool name matching. Command content-based filtering is NOT supported at matcher level.

| Supported | Not Supported |
|-----------|---------------|
| `Bash` (exact match) | `Bash(git:*)` |
| `Edit\|Write` (regex OR) | `Bash(kubectl:*)` |
| `Notebook.*` (regex pattern) | `tool_input.command` conditions |
| `*` (all tools) | glob patterns |

**Solution**: Filter by command content inside hook scripts using `jq`:

```bash
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command // ""')

# Only process git commands
if ! [[ "$command" =~ ^git ]]; then
  exit 0
fi
# ... validation logic
```

### 8. Dispatcher Pattern (Recommended for Multiple Hooks)

When you have multiple PreToolUse hooks for the same tool, consolidate into a single dispatcher to reduce log noise and improve performance.

**Problem**: Each hook runs separately, creating verbose session logs:
```
hook_progress: PreToolUse:Bash - script1.sh
hook_progress: PreToolUse:Bash - script2.sh
hook_progress: PreToolUse:Bash - script3.sh
... (repeated per Bash call)
```

**Solution**: Single dispatcher that routes by command pattern:

```bash
#!/bin/bash
# bash-pretooluse-dispatcher.sh

INPUT="${CLAUDE_TOOL_INPUT:-}"
[ -z "$INPUT" ] && INPUT=$(cat)

COMMAND=$(echo "$INPUT" | jq -r '.command // empty' 2>/dev/null)
[ -z "$COMMAND" ] && exit 0

BLOCKED=false

# Git commands
if [[ "$COMMAND" =~ ^git[[:space:]] ]]; then
  # Dangerous command check
  if [[ "$COMMAND" =~ (reset\ --hard|push\ --force|push\ -f\ ) ]]; then
    echo "BLOCK: Dangerous git command detected"
    BLOCKED=true
  fi

  # Commit validation
  if [[ "$COMMAND" =~ git[[:space:]]commit ]]; then
    # ... commit checks
    :
  fi
fi

# kubectl/helm commands
if [[ "$COMMAND" =~ ^(kubectl|helm)[[:space:]] ]]; then
  # Production delete guard
  if [[ "$COMMAND" =~ --context[[:space:]]+prod ]] && [[ "$COMMAND" =~ delete ]]; then
    echo "BLOCK: Production delete requires confirmation"
    BLOCKED=true
  fi
fi

# cat/echo file write guard
if [[ "$COMMAND" =~ (cat[[:space:]]*\<\<|echo[[:space:]].*\>) ]]; then
  if [[ "$COMMAND" =~ \>.*\.(md|yaml|json|sh|ts|js)$ ]]; then
    echo "BLOCK: Use Write tool instead of cat/echo"
    BLOCKED=true
  fi
fi

$BLOCKED && exit 1
exit 0
```

**Configuration**:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/scripts/bash-pretooluse-dispatcher.sh"
          }
        ]
      }
    ]
  }
}
```

**Benefits**:
- Single log entry per tool call
- Faster execution (one process vs many)
- Centralized logic, easier maintenance
- Conditional checks only run when relevant

## Important Notes

1. **Empty matcher**: Matches all tools
2. **exit 1**: Only blocks in PreToolUse
3. **Path spaces**: Quote `"$CLAUDE_FILE_PATHS"` required
4. **Ignore errors**: Use `2>/dev/null || true` to allow failures
5. **Performance**: PostToolUse runs on every tool use, keep commands lightweight
6. **Matcher scope**: Tool names only, not command content (use dispatcher for filtering)


path: resources/plugin-creation.md
content: # Plugin Creation Guide

Guide for open-source plugin distribution.

## Naming Restrictions

**IMPORTANT**: Marketplace names cannot impersonate official Anthropic/Claude marketplaces.

Reserved patterns (will be rejected):
- Names containing "official", "anthropic", or "claude" in official-sounding combinations
- Examples: `claude-plugins`, `anthropic-official`, `official-claude-tools`

Valid names:
- `es6kr-plugins`
- `mycompany-tools`
- `awesome-cc-plugins`

## Marketplace Structure

A marketplace is a repository containing multiple plugins.

```
marketplace-repo/                    # e.g., es6kr-plugins (NOT claude-plugins)
├── .claude-plugin/
│   └── marketplace.json            # Required: marketplace metadata
├── plugins/                        # Plugins folder
│   ├── code-quality/               # Individual plugin
│   │   ├── .claude-plugin/
│   │   │   └── plugin.json
│   │   ├── agents/
│   │   ├── skills/
│   │   ├── commands/
│   │   └── README.md
│   └── another-plugin/
├── external_plugins/               # External plugin references (optional)
└── README.md
```

## marketplace.json Structure

```json
{
  "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  "name": "marketplace-name",
  "description": "Marketplace description",
  "owner": {
    "name": "[Collect via AskUserQuestion]",
    "email": "[Collect via AskUserQuestion]"
  },
  "plugins": [
    {
      "name": "plugin-name",
      "description": "Plugin description",
      "version": "1.0.0",
      "author": {
        "name": "[Same as owner or specify separately]",
        "email": "[Same as owner or specify separately]"
      },
      "source": "./plugins/plugin-name",
      "category": "productivity",
      "homepage": "https://github.com/owner/repo/tree/main/plugins/plugin-name"
    }
  ]
}
```

## Individual Plugin Structure

```
plugin-name/
├── .claude-plugin/
│   └── plugin.json                 # Plugin metadata (optional)
├── agents/                         # Agent files
│   └── agent-name.md
├── skills/                         # Skill folders
│   └── skill-name/
│       └── SKILL.md
├── commands/                       # Slash commands
│   └── command-name.md
├── hooks/                          # Hook config (optional)
│   └── hooks.json
└── README.md                       # Plugin description
```

## Categories

| Category | Description |
|----------|-------------|
| `development` | Dev tools, LSP, SDK |
| `productivity` | Workflow, commit, PR |
| `testing` | Testing, E2E |
| `security` | Security checks |
| `learning` | Educational, explanatory |
| `database` | DB integration |
| `deployment` | Deployment |
| `monitoring` | Monitoring |
| `design` | Design |

## Metadata Collection

Collect via **AskUserQuestion** when creating marketplace:

```json
{
  "questions": [
    {
      "question": "Enter marketplace owner information",
      "header": "Owner",
      "options": [
        {"label": "Enter manually", "description": "Provide name and email"},
        {"label": "Use existing", "description": "Reuse previously entered info"}
      ],
      "multiSelect": false
    }
  ]
}
```

Additional items (if Other selected):
- Owner/author name
- Email address
- GitHub repository URL

## Workflow

### 1. Create Marketplace Repository

```bash
# Create with ghq
ghq create github.com/username/marketplace-name

# Create basic structure
cd $(ghq root)/github.com/username/marketplace-name
mkdir -p .claude-plugin plugins
```

### 2. Write marketplace.json

Create `.claude-plugin/marketplace.json` after collecting metadata.

### 3. Add Plugins

```bash
# Create new plugin directory
mkdir -p plugins/plugin-name/{agents,skills,commands}

# Copy existing automation
cp ~/.claude/agents/agent-name.md plugins/plugin-name/agents/
cp -r ~/.claude/skills/skill-name/ plugins/plugin-name/skills/
```

### 4. Generalize

When converting personal automation to open source:

- [ ] Remove hardcoded paths (e.g., `/Users/john/` → relative paths)
- [ ] Remove personal info (e.g., IP addresses, domains, names)
- [ ] Make configurable via environment variables
- [ ] Update description to be universal
- [ ] Write English README (for international distribution)

### 5. Write README

Include `README.md` for each plugin:
- Plugin description
- List of included agents/skills/commands
- Usage examples
- Configuration (if any)

### 6. Test

```bash
# Test local plugin installation
claude /install-plugin /path/to/plugins/plugin-name
```

### 7. Deploy

1. Push marketplace repository to GitHub
2. Visit claudemarketplaces.com
3. Request marketplace registration
4. Approval after review

## Official Marketplace Reference

Check official plugin marketplace structure:
- Location: `~/.claude/plugins/marketplaces/claude-plugins-official/`
- Repository: `anthropics/claude-plugins-official`

## Local Development Location

Develop directly in marketplaces folder:
- `~/.claude/plugins/marketplaces/marketplace-name/`

Then add via Claude Code:
```bash
~/.claude/plugins/marketplaces/marketplace-name
```

## License Considerations

### Using external code

When incorporating code from other projects:

1. **Check the license** of the source project
2. **BSD 3-Clause** (e.g., PyTorch): Can use with MIT, but must include BSD notice in the file
3. **MIT/Apache**: Generally compatible, include attribution

Example BSD notice in file:
```markdown
<!--
This file is derived from:
https://github.com/org/repo/path/to/file
Copyright (c) [Year] [Contributors]
Licensed under BSD 3-Clause License
SPDX-License-Identifier: BSD-3-Clause
-->
```

### Plugin dependencies

**Currently not supported.** Each plugin is independent.

Workaround for complementary plugins:
- Document in README that another plugin is recommended
- Name plugins to show relationship (e.g., `commit-reviewer` vs official `code-review`)
- Explain differences from similar official plugins


path: resources/rules-guide.md
content: # Rules Guide

Claude Code rules for AI behavior constraints and project conventions.

## Basic Structure

```markdown
# Rule Title

## Purpose
What this rule enforces

## Guidelines
- Specific constraint 1
- Specific constraint 2
- Specific constraint 3

## Examples

**Do:**
- Correct behavior example

**Don't:**
- Incorrect behavior example
```

## Location

| Scope | Path |
|-------|------|
| Global (all projects) | `~/.claude/rules/*.md` |
| Project-specific | `.claude/rules/*.md` |

Rules are automatically loaded at session start.

## Rule Categories

### 1. Code Style Rules

```markdown
# TypeScript Conventions

## Purpose
Enforce consistent TypeScript code style across the project.

## Guidelines
- Use `interface` over `type` for object shapes
- Prefer `const` assertions for literal types
- Always use explicit return types on exported functions
- No `any` type - use `unknown` if type is truly unknown

## Examples

**Do:**
```typescript
interface User {
  id: string;
  name: string;
}

export function getUser(id: string): Promise<User> {
  // ...
}
```

**Don't:**
```typescript
type User = { id: any; name: any };

export function getUser(id) {
  // ...
}
```
```

### 2. Git Workflow Rules

```markdown
# Git Commit Rules

## Purpose
Maintain consistent git history and commit quality.

## Guidelines
- Use Conventional Commit format (feat, fix, docs, etc.)
- Keep commits atomic - one logical change per commit
- Never force push to main/master
- Always sign commits with `-S` flag for open source

## Examples

**Do:**
```
feat(auth): add OAuth2 login flow
fix(api): handle null response from external service
```

**Don't:**
```
fixed stuff
WIP
asdf
```
```

### 3. Security Rules

```markdown
# Security Constraints

## Purpose
Prevent accidental security issues and data loss.

## Guidelines
- Never commit secrets or API keys
- Backup before destructive operations
- Validate user input at system boundaries
- Use parameterized queries for database operations

## Forbidden Commands (require user confirmation)
- `git reset --hard`
- `rm -rf` (use backup instead)
- `docker volume rm`
- Any command that deletes persistent data
```

### 4. Documentation Rules

```markdown
# Documentation Standards

## Purpose
Keep documentation current and useful.

## Guidelines
- Update README when adding features
- Document breaking changes immediately
- Keep CLAUDE.md concise - detail goes in separate docs
- Use Mermaid or PlantUML for diagrams
```

### 5. Architecture Rules

```markdown
# Project Architecture

## Purpose
Maintain consistent project structure and patterns.

## Guidelines
- Components in `src/components/`
- Utilities in `src/utils/`
- Types in `src/types/`
- Tests adjacent to source files (`*.test.ts`)

## File Size Limits
- Components: Max 200 lines (split if larger)
- Utility files: Max 150 lines
- Test files: No strict limit

## Import Order
1. External packages
2. Internal aliases (@/)
3. Relative imports
4. Type imports
```

## Multiple Rules Files

You can have multiple rule files for different concerns:

```
.claude/rules/
├── code-style.md
├── git-workflow.md
├── security.md
└── architecture.md
```

## Best Practices

1. **Be specific**: Vague rules are ignored. Give concrete examples.
2. **Keep focused**: One concern per rule file
3. **Include examples**: Show both correct and incorrect patterns
4. **Explain why**: Help understand the reasoning behind rules
5. **Update regularly**: Remove outdated rules, add new learnings

## Interaction with Other Types

| With | Behavior |
|------|----------|
| Skills | Rules constrain how skills operate |
| Agents | Agents inherit rules from session |
| Hooks | Hooks can enforce rules automatically |
| Commands | Commands follow rule constraints |


path: resources/slash-command-syntax.md
content: # Slash Command Syntax Reference

## File Location

| Level | Location | Scope |
|-------|----------|-------|
| Project | `.claude/commands/name.md` | Team, version controlled |
| Global | `~/.claude/commands/name.md` | Personal, all projects |

Project commands take precedence over global commands with the same name.

## Frontmatter Options

```yaml
---
allowed-tools: Bash(git:*), Read, Edit    # Tools the command can use
argument-hint: [issue-number] [priority]  # Expected arguments for /help
description: Brief description            # Shown in /help output
model: claude-3-5-haiku-20241022          # Specific model to use
disable-model-invocation: false           # Prevent SlashCommand tool from calling this
---
```

| Option | Purpose | Default |
|--------|---------|---------|
| `allowed-tools` | Tools the command can use | Inherits from conversation |
| `argument-hint` | Expected arguments display | None |
| `description` | Brief description in `/help` | First line of prompt |
| `model` | Specific model to use | Inherits from conversation |
| `disable-model-invocation` | Block SlashCommand tool access | false |

## Arguments

### All Arguments: `$ARGUMENTS`

```markdown
Fix issue #$ARGUMENTS following our coding standards.
```

Usage: `/fix-issue 123 high-priority`
Result: `Fix issue #123 high-priority following our coding standards.`

### Positional Arguments: `$1`, `$2`, `$3`, etc.

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

Review PR #$1 with priority $2 and assign to $3.
```

Usage: `/review-pr 456 high alice`
Result: `Review PR #456 with priority high and assign to alice.`

## Dynamic Content

### Bash Execution: `!`backtick`

Execute shell commands and embed output:

```markdown
## Context

- Current git status: !`git status`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -5`
- Changed files: !`git diff --name-only`

Based on the above, create a commit message.
```

### File References: `@path`

Include file contents inline:

```markdown
Review the implementation in @src/utils/helpers.js

Compare the old version @src/old.js with new @src/new.js
```

## Examples

### Simple Git Commit

```markdown
---
allowed-tools: Bash(git:*)
description: Create a conventional commit
---

Create a git commit with conventional commit format.
Current changes: !`git diff --staged`
```

### PR Review with Arguments

```markdown
---
allowed-tools: Read, Bash(gh:*)
argument-hint: [pr-number]
description: Review a GitHub PR
---

Review PR #$1:
- PR details: !`gh pr view $1`
- Changed files: !`gh pr diff $1 --name-only`

Focus on security, performance, and code style.
```

### Build Command for Monorepo

```markdown
---
allowed-tools: Bash(pnpm:*), Bash(code:*)
description: Build and install VSCode extension
---

Build the VSCode extension:

1. Build core: `pnpm --filter @claude-sessions/core build`
2. Package vsix: `pnpm --filter claude-sessions package`
3. Install: `code --install-extension packages/vscode-extension/claude-sessions-*.vsix --force`

Run all steps and report the result.
```

### Context-Aware Debug

```markdown
---
allowed-tools: Read, Bash(npm:*), Bash(node:*)
description: Debug current file with context
---

Debug the current issue:

Project info:
- Package.json: @package.json
- Node version: !`node --version`
- Dependencies: !`npm ls --depth=0`

Analyze and suggest fixes.
```

## Namespacing

Organize commands in subdirectories:

```
.claude/commands/
├── frontend/
│   ├── component.md    # /component (shown as "project:frontend")
│   └── test.md         # /test (shown as "project:frontend")
└── backend/
    ├── api.md          # /api (shown as "project:backend")
    └── migrate.md      # /migrate (shown as "project:backend")
```

## SlashCommand Tool Integration

Claude can invoke custom commands programmatically. To enable:

1. Add `description` in frontmatter
2. Reference command in prompts: "Run /build when code changes"

Character budget: 15,000 characters (configurable via `SLASH_COMMAND_TOOL_CHAR_BUDGET`)


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)