spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / plugins / plugin-dev / skills / plugin-structure / examples / standard-plugin.md
587 lines · 13.0 KBPreviewCodeRaw
1# Standard Plugin Example
2
3A well-structured plugin with commands, agents, and skills.
4
5## Directory Structure
6
7```
8code-quality/
9├── .claude-plugin/
10│ └── plugin.json
11├── commands/
12│ ├── lint.md
13│ ├── test.md
14│ └── review.md
15├── agents/
16│ ├── code-reviewer.md
17│ └── test-generator.md
18├── skills/
19│ ├── code-standards/
20│ │ ├── SKILL.md
21│ │ └── references/
22│ │ └── style-guide.md
23│ └── testing-patterns/
24│ ├── SKILL.md
25│ └── examples/
26│ ├── unit-test.js
27│ └── integration-test.js
28├── hooks/
29│ ├── hooks.json
30│ └── scripts/
31│ └── validate-commit.sh
32└── scripts/
33 ├── run-linter.sh
34 └── generate-report.py
35```
36
37## File Contents
38
39### .claude-plugin/plugin.json
40
41```json
42{
43 "name": "code-quality",
44 "version": "1.0.0",
45 "description": "Comprehensive code quality tools including linting, testing, and review automation",
46 "author": {
47 "name": "Quality Team",
48 "email": "quality@example.com"
49 },
50 "homepage": "https://docs.example.com/plugins/code-quality",
51 "repository": "https://github.com/example/code-quality-plugin",
52 "license": "MIT",
53 "keywords": ["code-quality", "linting", "testing", "code-review", "automation"]
54}
55```
56
57### commands/lint.md
58
59```markdown
60---
61name: lint
62description: Run linting checks on the codebase
63---
64
65# Lint Command
66
67Run comprehensive linting checks on the project codebase.
68
69## Process
70
711. Detect project type and installed linters
722. Run appropriate linters (ESLint, Pylint, RuboCop, etc.)
733. Collect and format results
744. Report issues with file locations and severity
75
76## Implementation
77
78Execute the linting script:
79
80\`\`\`bash
81bash ${CLAUDE_PLUGIN_ROOT}/scripts/run-linter.sh
82\`\`\`
83
84Parse the output and present issues organized by:
85- Critical issues (must fix)
86- Warnings (should fix)
87- Style suggestions (optional)
88
89For each issue, show:
90- File path and line number
91- Issue description
92- Suggested fix (if available)
93```
94
95### commands/test.md
96
97```markdown
98---
99name: test
100description: Run test suite with coverage reporting
101---
102
103# Test Command
104
105Execute the project test suite and generate coverage reports.
106
107## Process
108
1091. Identify test framework (Jest, pytest, RSpec, etc.)
1102. Run all tests
1113. Generate coverage report
1124. Identify untested code
113
114## Output
115
116Present results in structured format:
117- Test summary (passed/failed/skipped)
118- Coverage percentage by file
119- Critical untested areas
120- Failed test details
121
122## Integration
123
124After test completion, offer to:
125- Fix failing tests
126- Generate tests for untested code (using test-generator agent)
127- Update documentation based on test changes
128```
129
130### agents/code-reviewer.md
131
132```markdown
133---
134description: Expert code reviewer specializing in identifying bugs, security issues, and improvement opportunities
135capabilities:
136 - Analyze code for potential bugs and logic errors
137 - Identify security vulnerabilities
138 - Suggest performance improvements
139 - Ensure code follows project standards
140 - Review test coverage adequacy
141---
142
143# Code Reviewer Agent
144
145Specialized agent for comprehensive code review.
146
147## Expertise
148
149- **Bug detection**: Logic errors, edge cases, error handling
150- **Security analysis**: Injection vulnerabilities, authentication issues, data exposure
151- **Performance**: Algorithm efficiency, resource usage, optimization opportunities
152- **Standards compliance**: Style guide adherence, naming conventions, documentation
153- **Test coverage**: Adequacy of test cases, missing scenarios
154
155## Review Process
156
1571. **Initial scan**: Quick pass for obvious issues
1582. **Deep analysis**: Line-by-line review of changed code
1593. **Context evaluation**: Check impact on related code
1604. **Best practices**: Compare against project and language standards
1615. **Recommendations**: Prioritized list of improvements
162
163## Integration with Skills
164
165Automatically loads `code-standards` skill for project-specific guidelines.
166
167## Output Format
168
169For each file reviewed:
170- Overall assessment
171- Critical issues (must fix before merge)
172- Important issues (should fix)
173- Suggestions (nice to have)
174- Positive feedback (what was done well)
175```
176
177### agents/test-generator.md
178
179```markdown
180---
181description: Generates comprehensive test suites from code analysis
182capabilities:
183 - Analyze code structure and logic flow
184 - Generate unit tests for functions and methods
185 - Create integration tests for modules
186 - Design edge case and error condition tests
187 - Suggest test fixtures and mocks
188---
189
190# Test Generator Agent
191
192Specialized agent for generating comprehensive test suites.
193
194## Expertise
195
196- **Unit testing**: Individual function/method tests
197- **Integration testing**: Module interaction tests
198- **Edge cases**: Boundary conditions, error paths
199- **Test organization**: Proper test structure and naming
200- **Mocking**: Appropriate use of mocks and stubs
201
202## Generation Process
203
2041. **Code analysis**: Understand function purpose and logic
2052. **Path identification**: Map all execution paths
2063. **Input design**: Create test inputs covering all paths
2074. **Assertion design**: Define expected outputs
2085. **Test generation**: Write tests in project's framework
209
210## Integration with Skills
211
212Automatically loads `testing-patterns` skill for project-specific test conventions.
213
214## Test Quality
215
216Generated tests include:
217- Happy path scenarios
218- Edge cases and boundary conditions
219- Error handling verification
220- Mock data for external dependencies
221- Clear test descriptions
222```
223
224### skills/code-standards/SKILL.md
225
226```markdown
227---
228name: Code Standards
229description: This skill should be used when reviewing code, enforcing style guidelines, checking naming conventions, or ensuring code quality standards. Provides project-specific coding standards and best practices.
230version: 1.0.0
231---
232
233# Code Standards
234
235Comprehensive coding standards and best practices for maintaining code quality.
236
237## Overview
238
239Enforce consistent code quality through standardized conventions for:
240- Code style and formatting
241- Naming conventions
242- Documentation requirements
243- Error handling patterns
244- Security practices
245
246## Style Guidelines
247
248### Formatting
249
250- **Indentation**: 2 spaces (JavaScript/TypeScript), 4 spaces (Python)
251- **Line length**: Maximum 100 characters
252- **Braces**: Same line for opening brace (K&R style)
253- **Whitespace**: Space after commas, around operators
254
255### Naming Conventions
256
257- **Variables**: camelCase for JavaScript, snake_case for Python
258- **Functions**: camelCase, descriptive verb-noun pairs
259- **Classes**: PascalCase
260- **Constants**: UPPER_SNAKE_CASE
261- **Files**: kebab-case for modules
262
263## Documentation Requirements
264
265### Function Documentation
266
267Every function must include:
268- Purpose description
269- Parameter descriptions with types
270- Return value description with type
271- Example usage (for public functions)
272
273### Module Documentation
274
275Every module must include:
276- Module purpose
277- Public API overview
278- Usage examples
279- Dependencies
280
281## Error Handling
282
283### Required Practices
284
285- Never swallow errors silently
286- Always log errors with context
287- Use specific error types
288- Provide actionable error messages
289- Clean up resources in finally blocks
290
291### Example Pattern
292
293\`\`\`javascript
294async function processData(data) {
295 try {
296 const result = await transform(data)
297 return result
298 } catch (error) {
299 logger.error('Data processing failed', {
300 data: sanitize(data),
301 error: error.message,
302 stack: error.stack
303 })
304 throw new DataProcessingError('Failed to process data', { cause: error })
305 }
306}
307\`\`\`
308
309## Security Practices
310
311- Validate all external input
312- Sanitize data before output
313- Use parameterized queries
314- Never log sensitive information
315- Keep dependencies updated
316
317## Detailed Guidelines
318
319For comprehensive style guides by language, see:
320- `references/style-guide.md`
321```
322
323### skills/code-standards/references/style-guide.md
324
325```markdown
326# Comprehensive Style Guide
327
328Detailed style guidelines for all supported languages.
329
330## JavaScript/TypeScript
331
332### Variable Declarations
333
334Use `const` by default, `let` when reassignment needed, never `var`:
335
336\`\`\`javascript
337// Good
338const MAX_RETRIES = 3
339let currentTry = 0
340
341// Bad
342var MAX_RETRIES = 3
343\`\`\`
344
345### Function Declarations
346
347Use function expressions for consistency:
348
349\`\`\`javascript
350// Good
351const calculateTotal = (items) => {
352 return items.reduce((sum, item) => sum + item.price, 0)
353}
354
355// Bad (inconsistent style)
356function calculateTotal(items) {
357 return items.reduce((sum, item) => sum + item.price, 0)
358}
359\`\`\`
360
361### Async/Await
362
363Prefer async/await over promise chains:
364
365\`\`\`javascript
366// Good
367async function fetchUserData(userId) {
368 const user = await db.getUser(userId)
369 const orders = await db.getOrders(user.id)
370 return { user, orders }
371}
372
373// Bad
374function fetchUserData(userId) {
375 return db.getUser(userId)
376 .then(user => db.getOrders(user.id)
377 .then(orders => ({ user, orders })))
378}
379\`\`\`
380
381## Python
382
383### Import Organization
384
385Order imports: standard library, third-party, local:
386
387\`\`\`python
388# Good
389import os
390import sys
391
392import numpy as np
393import pandas as pd
394
395from app.models import User
396from app.utils import helper
397
398# Bad - mixed order
399from app.models import User
400import numpy as np
401import os
402\`\`\`
403
404### Type Hints
405
406Use type hints for all function signatures:
407
408\`\`\`python
409# Good
410def calculate_average(numbers: list[float]) -> float:
411 return sum(numbers) / len(numbers)
412
413# Bad
414def calculate_average(numbers):
415 return sum(numbers) / len(numbers)
416\`\`\`
417
418## Additional Languages
419
420See language-specific guides for:
421- Go: `references/go-style.md`
422- Rust: `references/rust-style.md`
423- Ruby: `references/ruby-style.md`
424```
425
426### hooks/hooks.json
427
428```json
429{
430 "PreToolUse": [
431 {
432 "matcher": "Write|Edit",
433 "hooks": [
434 {
435 "type": "prompt",
436 "prompt": "Before modifying code, verify it meets our coding standards from the code-standards skill. Check formatting, naming conventions, and documentation. If standards aren't met, suggest improvements.",
437 "timeout": 30
438 }
439 ]
440 }
441 ],
442 "Stop": [
443 {
444 "matcher": ".*",
445 "hooks": [
446 {
447 "type": "command",
448 "command": "bash ${CLAUDE_PLUGIN_ROOT}/hooks/scripts/validate-commit.sh",
449 "timeout": 45
450 }
451 ]
452 }
453 ]
454}
455```
456
457### hooks/scripts/validate-commit.sh
458
459```bash
460#!/bin/bash
461# Validate code quality before task completion
462
463set -e
464
465# Check if there are any uncommitted changes
466if [[ -z $(git status -s) ]]; then
467 echo '{"systemMessage": "No changes to validate. Task complete."}'
468 exit 0
469fi
470
471# Run linter on changed files
472CHANGED_FILES=$(git diff --name-only --cached | grep -E '\.(js|ts|py)$' || true)
473
474if [[ -z "$CHANGED_FILES" ]]; then
475 echo '{"systemMessage": "No code files changed. Validation passed."}'
476 exit 0
477fi
478
479# Run appropriate linters
480ISSUES=0
481
482for file in $CHANGED_FILES; do
483 case "$file" in
484 *.js|*.ts)
485 if ! npx eslint "$file" --quiet; then
486 ISSUES=$((ISSUES + 1))
487 fi
488 ;;
489 *.py)
490 if ! python -m pylint "$file" --errors-only; then
491 ISSUES=$((ISSUES + 1))
492 fi
493 ;;
494 esac
495done
496
497if [[ $ISSUES -gt 0 ]]; then
498 echo "{\"systemMessage\": \"Found $ISSUES code quality issues. Please fix before completing.\"}"
499 exit 1
500fi
501
502echo '{"systemMessage": "Code quality checks passed. Ready to commit."}'
503exit 0
504```
505
506## Usage Examples
507
508### Running Commands
509
510```
511$ claude
512> /lint
513Running linter checks...
514
515Critical Issues (2):
516 src/api/users.js:45 - SQL injection vulnerability
517 src/utils/helpers.js:12 - Unhandled promise rejection
518
519Warnings (5):
520 src/components/Button.tsx:23 - Missing PropTypes
521 ...
522
523Style Suggestions (8):
524 src/index.js:1 - Use const instead of let
525 ...
526
527> /test
528Running test suite...
529
530Test Results:
531 ✓ 245 passed
532 ✗ 3 failed
533 ○ 2 skipped
534
535Coverage: 87.3%
536
537Untested Files:
538 src/utils/cache.js - 0% coverage
539 src/api/webhooks.js - 23% coverage
540
541Failed Tests:
542 1. User API › GET /users › should handle pagination
543 Expected 200, received 500
544 ...
545```
546
547### Using Agents
548
549```
550> Review the changes in src/api/users.js
551
552[code-reviewer agent selected automatically]
553
554Code Review: src/api/users.js
555
556Critical Issues:
557 1. Line 45: SQL injection vulnerability
558 - Using string concatenation for SQL query
559 - Replace with parameterized query
560 - Priority: CRITICAL
561
562 2. Line 67: Missing error handling
563 - Database query without try/catch
564 - Could crash server on DB error
565 - Priority: HIGH
566
567Suggestions:
568 1. Line 23: Consider caching user data
569 - Frequent DB queries for same users
570 - Add Redis caching layer
571 - Priority: MEDIUM
572```
573
574## Key Points
575
5761. **Complete manifest**: All recommended metadata fields
5772. **Multiple components**: Commands, agents, skills, hooks
5783. **Rich skills**: References and examples for detailed information
5794. **Automation**: Hooks enforce standards automatically
5805. **Integration**: Components work together cohesively
581
582## When to Use This Pattern
583
584- Production plugins for distribution
585- Team collaboration tools
586- Plugins requiring consistency enforcement
587- Complex workflows with multiple entry points