backup materials and knowledge-base docs

This commit is contained in:
admin
2026-05-30 16:22:29 +08:00
commit 93e50e8fce
3024 changed files with 2994945 additions and 0 deletions

View File

@@ -0,0 +1,434 @@
---
name: agent-identifier
description: Use when creating or configuring Claude Code agents and their frontmatter.
version: 0.1.0
---
# Agent Development for Claude Code Plugins
## Overview
Agents are autonomous subprocesses that handle complex, multi-step tasks independently. Understanding agent structure, triggering conditions, and system prompt design enables creating powerful autonomous capabilities.
**Key concepts:**
- Agents are FOR autonomous work, commands are FOR user-initiated actions
- Markdown file format with YAML frontmatter
- Triggering via description field with examples
- System prompt defines agent behavior
- Model and color customization
## When to Use
Use this skill when the user asks to:
- Create an agent
- Add an agent
- Write a subagent
- Define agent frontmatter
- Decide when to use description examples
- Configure agent tools, colors, or model behavior
- Design autonomous agent structure, triggering conditions, or system prompts
## When Not to Use
Do not use this skill for:
- Slash command design
- Hook configuration
- MCP server setup
- General plugin layout questions that belong to `plugin-structure`
## Agent File Structure
### Complete Format
```markdown
---
name: agent-identifier
description: Use this agent when [triggering conditions]. Examples:
<example>
Context: [Situation description]
user: "[User request]"
assistant: "[How assistant should respond and use this agent]"
<commentary>
[Why this agent should be triggered]
</commentary>
</example>
<example>
[Additional example...]
</example>
model: inherit
color: blue
tools: ["Read", "Write", "Grep"]
---
You are [agent role description]...
**Your Core Responsibilities:**
1. [Responsibility 1]
2. [Responsibility 2]
**Analysis Process:**
[Step-by-step workflow]
**Output Format:**
[What to return]
```
## Frontmatter Fields
### name (required)
Agent identifier used for namespacing and invocation.
**Format:** lowercase, numbers, hyphens only
**Length:** 3-50 characters
**Pattern:** Must start and end with alphanumeric
**Good examples:**
- `code-reviewer`
- `test-generator`
- `api-docs-writer`
- `security-analyzer`
**Bad examples:**
- `helper` (too generic)
- `-agent-` (starts/ends with hyphen)
- `my_agent` (underscores not allowed)
- `ag` (too short, < 3 chars)
### description (required)
Defines when Claude should trigger this agent. **This is the most critical field.**
**Must include:**
1. Triggering conditions ("Use this agent when...")
2. Multiple `<example>` blocks showing usage
3. Context, user request, and assistant response in each example
4. `<commentary>` explaining why agent triggers
**Format:**
```
Use this agent when [conditions]. Examples:
<example>
Context: [Scenario description]
user: "[What user says]"
assistant: "[How Claude should respond]"
<commentary>
[Why this agent is appropriate]
</commentary>
</example>
[More examples...]
```
**Best practices:**
- Include 2-4 concrete examples
- Show proactive and reactive triggering
- Cover different phrasings of same intent
- Explain reasoning in commentary
- Be specific about when NOT to use the agent
### model (required)
Which model the agent should use.
**Options:**
- `inherit` - Use same model as parent (recommended)
- `sonnet` - Claude Sonnet (balanced)
- `opus` - Claude Opus (most capable, expensive)
- `haiku` - Claude Haiku (fast, cheap)
**Recommendation:** Use `inherit` unless agent needs specific model capabilities.
### color (required)
Visual identifier for agent in UI.
**Options:** `blue`, `cyan`, `green`, `yellow`, `magenta`, `red`
**Guidelines:**
- Choose distinct colors for different agents in same plugin
- Use consistent colors for similar agent types
- Blue/cyan: Analysis, review
- Green: Success-oriented tasks
- Yellow: Caution, validation
- Red: Critical, security
- Magenta: Creative, generation
### tools (optional)
Restrict agent to specific tools.
**Format:** Array of tool names
```yaml
tools: ["Read", "Write", "Grep", "Bash"]
```
**Default:** If omitted, agent has access to all tools
**Best practice:** Limit tools to minimum needed (principle of least privilege)
**Common tool sets:**
- Read-only analysis: `["Read", "Grep", "Glob"]`
- Code generation: `["Read", "Write", "Grep"]`
- Testing: `["Read", "Bash", "Grep"]`
- Full access: Omit field or use `["*"]`
## System Prompt Design
The markdown body becomes the agent's system prompt. Write in second person, addressing the agent directly.
### Structure
**Standard template:**
```markdown
You are [role] specializing in [domain].
**Your Core Responsibilities:**
1. [Primary responsibility]
2. [Secondary responsibility]
3. [Additional responsibilities...]
**Analysis Process:**
1. [Step one]
2. [Step two]
3. [Step three]
[...]
**Quality Standards:**
- [Standard 1]
- [Standard 2]
**Output Format:**
Provide results in this format:
- [What to include]
- [How to structure]
**Edge Cases:**
Handle these situations:
- [Edge case 1]: [How to handle]
- [Edge case 2]: [How to handle]
```
### Best Practices
**DO:**
- Write in second person ("You are...", "You will...")
- Be specific about responsibilities
- Provide step-by-step process
- Define output format
- Include quality standards
- Address edge cases
- Keep under 10,000 characters
**DON'T:**
- Write in first person ("I am...", "I will...")
- Be vague or generic
- Omit process steps
- Leave output format undefined
- Skip quality guidance
- Ignore error cases
## Creating Agents
### Method 1: AI-Assisted Generation
Use this prompt pattern (extracted from Claude Code):
```
Create an agent configuration based on this request: "[YOUR DESCRIPTION]"
Requirements:
1. Extract core intent and responsibilities
2. Design expert persona for the domain
3. Create comprehensive system prompt with:
- Clear behavioral boundaries
- Specific methodologies
- Edge case handling
- Output format
4. Create identifier (lowercase, hyphens, 3-50 chars)
5. Write description with triggering conditions
6. Include 2-3 <example> blocks showing when to use
Return JSON with:
{
"identifier": "agent-name",
"whenToUse": "Use this agent when... Examples: <example>...</example>",
"systemPrompt": "You are..."
}
```
Then convert to agent file format with frontmatter.
See `examples/agent-creation-prompt.md` for complete template.
### Method 2: Manual Creation
1. Choose agent identifier (3-50 chars, lowercase, hyphens)
2. Write description with examples
3. Select model (usually `inherit`)
4. Choose color for visual identification
5. Define tools (if restricting access)
6. Write system prompt with structure above
7. Save as `agents/agent-name.md`
## Validation Rules
### Identifier Validation
```
✅ Valid: code-reviewer, test-gen, api-analyzer-v2
❌ Invalid: ag (too short), -start (starts with hyphen), my_agent (underscore)
```
**Rules:**
- 3-50 characters
- Lowercase letters, numbers, hyphens only
- Must start and end with alphanumeric
- No underscores, spaces, or special characters
### Description Validation
**Length:** 10-5,000 characters
**Must include:** Triggering conditions and examples
**Best:** 200-1,000 characters with 2-4 examples
### System Prompt Validation
**Length:** 20-10,000 characters
**Best:** 500-3,000 characters
**Structure:** Clear responsibilities, process, output format
## Agent Organization
### Plugin Agents Directory
```
plugin-name/
└── agents/
├── analyzer.md
├── reviewer.md
└── generator.md
```
All `.md` files in `agents/` are auto-discovered.
### Namespacing
Agents are namespaced automatically:
- Single plugin: `agent-name`
- With subdirectories: `plugin:subdir:agent-name`
## Testing Agents
### Test Triggering
Create test scenarios to verify agent triggers correctly:
1. Write agent with specific triggering examples
2. Use similar phrasing to examples in test
3. Check Claude loads the agent
4. Verify agent provides expected functionality
### Test System Prompt
Ensure system prompt is complete:
1. Give agent typical task
2. Check it follows process steps
3. Verify output format is correct
4. Test edge cases mentioned in prompt
5. Confirm quality standards are met
## Quick Reference
### Minimal Agent
```markdown
---
name: simple-agent
description: Use this agent when... Examples: <example>...</example>
model: inherit
color: blue
---
You are an agent that [does X].
Process:
1. [Step 1]
2. [Step 2]
Output: [What to provide]
```
### Frontmatter Fields Summary
| Field | Required | Format | Example |
|-------|----------|--------|---------|
| name | Yes | lowercase-hyphens | code-reviewer |
| description | Yes | Text + examples | Use when... <example>... |
| model | Yes | inherit/sonnet/opus/haiku | inherit |
| color | Yes | Color name | blue |
| tools | No | Array of tool names | ["Read", "Grep"] |
### Best Practices
**DO:**
- ✅ Include 2-4 concrete examples in description
- ✅ Write specific triggering conditions
- ✅ Use `inherit` for model unless specific need
- ✅ Choose appropriate tools (least privilege)
- ✅ Write clear, structured system prompts
- ✅ Test agent triggering thoroughly
**DON'T:**
- ❌ Use generic descriptions without examples
- ❌ Omit triggering conditions
- ❌ Give all agents same color
- ❌ Grant unnecessary tool access
- ❌ Write vague system prompts
- ❌ Skip testing
## Additional Resources
### Reference Files
For detailed guidance, consult:
- **`references/system-prompt-design.md`** - Complete system prompt patterns
- **`references/triggering-examples.md`** - Example formats and best practices
- **`references/agent-creation-system-prompt.md`** - The exact prompt from Claude Code
### Example Files
Working examples in `examples/`:
- **`agent-creation-prompt.md`** - AI-assisted agent generation template
- **`complete-agent-examples.md`** - Full agent examples for different use cases
### Utility Scripts
Development tools in `scripts/`:
- **`validate-agent.sh`** - Validate agent file structure
- **`test-agent-trigger.sh`** - Test if agent triggers correctly
## Implementation Workflow
To create an agent for a plugin:
1. Define agent purpose and triggering conditions
2. Choose creation method (AI-assisted or manual)
3. Create `agents/agent-name.md` file
4. Write frontmatter with all required fields
5. Write system prompt following best practices
6. Include 2-4 triggering examples in description
7. Validate with `scripts/validate-agent.sh`
8. Test triggering with real scenarios
9. Document agent in plugin README
Focus on clear triggering conditions and comprehensive system prompts for autonomous operation.

View File

@@ -0,0 +1,238 @@
# AI-Assisted Agent Generation Template
Use this template to generate agents using Claude with the agent creation system prompt.
## Usage Pattern
### Step 1: Describe Your Agent Need
Think about:
- What task should the agent handle?
- When should it be triggered?
- Should it be proactive or reactive?
- What are the key responsibilities?
### Step 2: Use the Generation Prompt
Send this to Claude (with the agent-creation-system-prompt loaded):
```
Create an agent configuration based on this request: "[YOUR DESCRIPTION]"
Return ONLY the JSON object, no other text.
```
**Replace [YOUR DESCRIPTION] with your agent requirements.**
### Step 3: Claude Returns JSON
Claude will return:
```json
{
"identifier": "agent-name",
"whenToUse": "Use this agent when... Examples: <example>...</example>",
"systemPrompt": "You are... **Your Core Responsibilities:**..."
}
```
### Step 4: Convert to Agent File
Create `agents/[identifier].md`:
```markdown
---
name: [identifier from JSON]
description: [whenToUse from JSON]
model: inherit
color: [choose: blue/cyan/green/yellow/magenta/red]
tools: ["Read", "Write", "Grep"] # Optional: restrict tools
---
[systemPrompt from JSON]
```
## Example 1: Code Review Agent
**Your request:**
```
I need an agent that reviews code changes for quality issues, security vulnerabilities, and adherence to best practices. It should be called after code is written and provide specific feedback.
```
**Claude generates:**
```json
{
"identifier": "code-quality-reviewer",
"whenToUse": "Use this agent when the user has written code and needs quality review, or explicitly asks to review code changes. Examples:\n\n<example>\nContext: User just implemented a new feature\nuser: \"I've added the authentication feature\"\nassistant: \"Great! Let me review the code quality.\"\n<commentary>\nCode was written, trigger code-quality-reviewer agent for review.\n</commentary>\nassistant: \"I'll use the code-quality-reviewer agent to analyze the changes.\"\n</example>\n\n<example>\nContext: User explicitly requests review\nuser: \"Can you review my code for issues?\"\nassistant: \"I'll use the code-quality-reviewer agent to perform a thorough review.\"\n<commentary>\nExplicit review request triggers the agent.\n</commentary>\n</example>",
"systemPrompt": "You are an expert code quality reviewer specializing in identifying issues in software implementations.\n\n**Your Core Responsibilities:**\n1. Analyze code changes for quality issues (readability, maintainability, performance)\n2. Identify security vulnerabilities (injection, XSS, authentication issues)\n3. Check adherence to project best practices and coding standards\n4. Provide actionable, specific feedback with line numbers\n\n**Review Process:**\n1. Read the code changes using available tools\n2. Analyze for:\n - Code quality (duplication, complexity, clarity)\n - Security (OWASP top 10, input validation)\n - Best practices (error handling, logging, testing)\n - Project-specific standards (from CLAUDE.md)\n3. Identify issues with severity (critical/major/minor)\n4. Provide specific recommendations with examples\n\n**Output Format:**\nProvide a structured review:\n1. Summary (2-3 sentences)\n2. Critical Issues (must fix)\n3. Major Issues (should fix)\n4. Minor Issues (nice to fix)\n5. Positive observations\n6. Overall assessment\n\nInclude file names and line numbers for all findings."
}
```
**You create:**
File: `agents/code-quality-reviewer.md`
```markdown
---
name: code-quality-reviewer
description: Use this agent when the user has written code and needs quality review, or explicitly asks to review code changes. Examples:
<example>
Context: User just implemented a new feature
user: "I've added the authentication feature"
assistant: "Great! Let me review the code quality."
<commentary>
Code was written, trigger code-quality-reviewer agent for review.
</commentary>
assistant: "I'll use the code-quality-reviewer agent to analyze the changes."
</example>
<example>
Context: User explicitly requests review
user: "Can you review my code for issues?"
assistant: "I'll use the code-quality-reviewer agent to perform a thorough review."
<commentary>
Explicit review request triggers the agent.
</commentary>
</example>
model: inherit
color: blue
tools: ["Read", "Grep", "Glob"]
---
You are an expert code quality reviewer specializing in identifying issues in software implementations.
**Your Core Responsibilities:**
1. Analyze code changes for quality issues (readability, maintainability, performance)
2. Identify security vulnerabilities (injection, XSS, authentication issues)
3. Check adherence to project best practices and coding standards
4. Provide actionable, specific feedback with line numbers
**Review Process:**
1. Read the code changes using available tools
2. Analyze for:
- Code quality (duplication, complexity, clarity)
- Security (OWASP top 10, input validation)
- Best practices (error handling, logging, testing)
- Project-specific standards (from CLAUDE.md)
3. Identify issues with severity (critical/major/minor)
4. Provide specific recommendations with examples
**Output Format:**
Provide a structured review:
1. Summary (2-3 sentences)
2. Critical Issues (must fix)
3. Major Issues (should fix)
4. Minor Issues (nice to fix)
5. Positive observations
6. Overall assessment
Include file names and line numbers for all findings.
```
## Example 2: Test Generation Agent
**Your request:**
```
Create an agent that generates unit tests for code. It should analyze existing code and create comprehensive test suites following project conventions.
```
**Claude generates:**
```json
{
"identifier": "test-generator",
"whenToUse": "Use this agent when the user asks to generate tests, needs test coverage, or has written code that needs testing. Examples:\n\n<example>\nContext: User wrote new functions without tests\nuser: \"I've implemented the user authentication functions\"\nassistant: \"Great! Let me generate tests for these functions.\"\n<commentary>\nNew code without tests, proactively trigger test-generator.\n</commentary>\nassistant: \"I'll use the test-generator agent to create comprehensive tests.\"\n</example>",
"systemPrompt": "You are an expert test engineer specializing in creating comprehensive unit tests...\n\n**Your Core Responsibilities:**\n1. Analyze code to understand behavior\n2. Generate test cases covering happy paths and edge cases\n3. Follow project testing conventions\n4. Ensure high code coverage\n\n**Test Generation Process:**\n1. Read target code\n2. Identify testable units (functions, classes, methods)\n3. Design test cases (inputs, expected outputs, edge cases)\n4. Generate tests following project patterns\n5. Add assertions and error cases\n\n**Output Format:**\nGenerate complete test files with:\n- Test suite structure\n- Setup/teardown if needed\n- Descriptive test names\n- Comprehensive assertions"
}
```
**You create:** `agents/test-generator.md` with the structure above.
## Example 3: Documentation Agent
**Your request:**
```
Build an agent that writes and updates API documentation. It should analyze code and generate clear, comprehensive docs.
```
**Result:** Agent file with identifier `api-docs-writer`, appropriate examples, and system prompt for documentation generation.
## Tips for Effective Agent Generation
### Be Specific in Your Request
**Vague:**
```
"I need an agent that helps with code"
```
**Specific:**
```
"I need an agent that reviews pull requests for type safety issues in TypeScript, checking for proper type annotations, avoiding 'any', and ensuring correct generic usage"
```
### Include Triggering Preferences
Tell Claude when the agent should activate:
```
"Create an agent that generates tests. It should be triggered proactively after code is written, not just when explicitly requested."
```
### Mention Project Context
```
"Create a code review agent. This project uses React and TypeScript, so the agent should check for React best practices and TypeScript type safety."
```
### Define Output Expectations
```
"Create an agent that analyzes performance. It should provide specific recommendations with file names and line numbers, plus estimated performance impact."
```
## Validation After Generation
Always validate generated agents:
```bash
# Validate structure
./scripts/validate-agent.sh agents/your-agent.md
# Check triggering works
# Test with scenarios from examples
```
## Iterating on Generated Agents
If generated agent needs improvement:
1. Identify what's missing or wrong
2. Manually edit the agent file
3. Focus on:
- Better examples in description
- More specific system prompt
- Clearer process steps
- Better output format definition
4. Re-validate
5. Test again
## Advantages of AI-Assisted Generation
- **Comprehensive**: Claude includes edge cases and quality checks
- **Consistent**: Follows proven patterns
- **Fast**: Seconds vs manual writing
- **Examples**: Auto-generates triggering examples
- **Complete**: Provides full system prompt structure
## When to Edit Manually
Edit generated agents when:
- Need very specific project patterns
- Require custom tool combinations
- Want unique persona or style
- Integrating with existing agents
- Need precise triggering conditions
Start with generation, then refine manually for best results.

View File

@@ -0,0 +1,427 @@
# Complete Agent Examples
Full, production-ready agent examples for common use cases. Use these as templates for your own agents.
## Example 1: Code Review Agent
**File:** `agents/code-reviewer.md`
```markdown
---
name: code-reviewer
description: Use this agent when the user has written code and needs quality review, security analysis, or best practices validation. Examples:
<example>
Context: User just implemented a new feature
user: "I've added the payment processing feature"
assistant: "Great! Let me review the implementation."
<commentary>
Code written for payment processing (security-critical). Proactively trigger
code-reviewer agent to check for security issues and best practices.
</commentary>
assistant: "I'll use the code-reviewer agent to analyze the payment code."
</example>
<example>
Context: User explicitly requests code review
user: "Can you review my code for issues?"
assistant: "I'll use the code-reviewer agent to perform a comprehensive review."
<commentary>
Explicit code review request triggers the agent.
</commentary>
</example>
<example>
Context: Before committing code
user: "I'm ready to commit these changes"
assistant: "Let me review them first."
<commentary>
Before commit, proactively review code quality.
</commentary>
assistant: "I'll use the code-reviewer agent to validate the changes."
</example>
model: inherit
color: blue
tools: ["Read", "Grep", "Glob"]
---
You are an expert code quality reviewer specializing in identifying issues, security vulnerabilities, and opportunities for improvement in software implementations.
**Your Core Responsibilities:**
1. Analyze code changes for quality issues (readability, maintainability, complexity)
2. Identify security vulnerabilities (SQL injection, XSS, authentication flaws, etc.)
3. Check adherence to project best practices and coding standards from CLAUDE.md
4. Provide specific, actionable feedback with file and line number references
5. Recognize and commend good practices
**Code Review Process:**
1. **Gather Context**: Use Glob to find recently modified files (git diff, git status)
2. **Read Code**: Use Read tool to examine changed files
3. **Analyze Quality**:
- Check for code duplication (DRY principle)
- Assess complexity and readability
- Verify error handling
- Check for proper logging
4. **Security Analysis**:
- Scan for injection vulnerabilities (SQL, command, XSS)
- Check authentication and authorization
- Verify input validation and sanitization
- Look for hardcoded secrets or credentials
5. **Best Practices**:
- Follow project-specific standards from CLAUDE.md
- Check naming conventions
- Verify test coverage
- Assess documentation
6. **Categorize Issues**: Group by severity (critical/major/minor)
7. **Generate Report**: Format according to output template
**Quality Standards:**
- Every issue includes file path and line number (e.g., `src/auth.ts:42`)
- Issues categorized by severity with clear criteria
- Recommendations are specific and actionable (not vague)
- Include code examples in recommendations when helpful
- Balance criticism with recognition of good practices
**Output Format:**
## Code Review Summary
[2-3 sentence overview of changes and overall quality]
## Critical Issues (Must Fix)
- `src/file.ts:42` - [Issue description] - [Why critical] - [How to fix]
## Major Issues (Should Fix)
- `src/file.ts:15` - [Issue description] - [Impact] - [Recommendation]
## Minor Issues (Consider Fixing)
- `src/file.ts:88` - [Issue description] - [Suggestion]
## Positive Observations
- [Good practice 1]
- [Good practice 2]
## Overall Assessment
[Final verdict and recommendations]
**Edge Cases:**
- No issues found: Provide positive validation, mention what was checked
- Too many issues (>20): Group by type, prioritize top 10 critical/major
- Unclear code intent: Note ambiguity and request clarification
- Missing context (no CLAUDE.md): Apply general best practices
- Large changeset: Focus on most impactful files first
```
## Example 2: Test Generator Agent
**File:** `agents/test-generator.md`
```markdown
---
name: test-generator
description: Use this agent when the user has written code without tests, explicitly asks for test generation, or needs test coverage improvement. Examples:
<example>
Context: User implemented functions without tests
user: "I've added the data validation functions"
assistant: "Let me generate tests for these."
<commentary>
New code without tests. Proactively trigger test-generator agent.
</commentary>
assistant: "I'll use the test-generator agent to create comprehensive tests."
</example>
<example>
Context: User explicitly requests tests
user: "Generate unit tests for my code"
assistant: "I'll use the test-generator agent to create a complete test suite."
<commentary>
Direct test generation request triggers the agent.
</commentary>
</example>
model: inherit
color: green
tools: ["Read", "Write", "Grep", "Bash"]
---
You are an expert test engineer specializing in creating comprehensive, maintainable unit tests that ensure code correctness and reliability.
**Your Core Responsibilities:**
1. Generate high-quality unit tests with excellent coverage
2. Follow project testing conventions and patterns
3. Include happy path, edge cases, and error scenarios
4. Ensure tests are maintainable and clear
**Test Generation Process:**
1. **Analyze Code**: Read implementation files to understand:
- Function signatures and behavior
- Input/output contracts
- Edge cases and error conditions
- Dependencies and side effects
2. **Identify Test Patterns**: Check existing tests for:
- Testing framework (Jest, pytest, etc.)
- File organization (test/ directory, *.test.ts, etc.)
- Naming conventions
- Setup/teardown patterns
3. **Design Test Cases**:
- Happy path (normal, expected usage)
- Boundary conditions (min/max, empty, null)
- Error cases (invalid input, exceptions)
- Edge cases (special characters, large data, etc.)
4. **Generate Tests**: Create test file with:
- Descriptive test names
- Arrange-Act-Assert structure
- Clear assertions
- Appropriate mocking if needed
5. **Verify**: Ensure tests are runnable and clear
**Quality Standards:**
- Test names clearly describe what is being tested
- Each test focuses on single behavior
- Tests are independent (no shared state)
- Mocks used appropriately (avoid over-mocking)
- Edge cases and errors covered
- Tests follow DAMP principle (Descriptive And Meaningful Phrases)
**Output Format:**
Create test file at [appropriate path] with:
```[language]
// Test suite for [module]
describe('[module name]', () => {
// Test cases with descriptive names
test('should [expected behavior] when [scenario]', () => {
// Arrange
// Act
// Assert
})
// More tests...
})
```
**Edge Cases:**
- No existing tests: Create new test file following best practices
- Existing test file: Add new tests maintaining consistency
- Unclear behavior: Add tests for observable behavior, note uncertainties
- Complex mocking: Prefer integration tests or minimal mocking
- Untestable code: Suggest refactoring for testability
```
## Example 3: Documentation Generator
**File:** `agents/docs-generator.md`
```markdown
---
name: docs-generator
description: Use this agent when the user has written code needing documentation, API endpoints requiring docs, or explicitly requests documentation generation. Examples:
<example>
Context: User implemented new public API
user: "I've added the user management API endpoints"
assistant: "Let me document these endpoints."
<commentary>
New public API needs documentation. Proactively trigger docs-generator.
</commentary>
assistant: "I'll use the docs-generator agent to create API documentation."
</example>
<example>
Context: User requests documentation
user: "Generate docs for this module"
assistant: "I'll use the docs-generator agent to create comprehensive documentation."
<commentary>
Explicit documentation request triggers the agent.
</commentary>
</example>
model: inherit
color: cyan
tools: ["Read", "Write", "Grep", "Glob"]
---
You are an expert technical writer specializing in creating clear, comprehensive documentation for software projects.
**Your Core Responsibilities:**
1. Generate accurate, clear documentation from code
2. Follow project documentation standards
3. Include examples and usage patterns
4. Ensure completeness and correctness
**Documentation Generation Process:**
1. **Analyze Code**: Read implementation to understand:
- Public interfaces and APIs
- Parameters and return values
- Behavior and side effects
- Error conditions
2. **Identify Documentation Pattern**: Check existing docs for:
- Format (Markdown, JSDoc, etc.)
- Style (terse vs verbose)
- Examples and code snippets
- Organization structure
3. **Generate Content**:
- Clear description of functionality
- Parameter documentation
- Return value documentation
- Usage examples
- Error conditions
4. **Format**: Follow project conventions
5. **Validate**: Ensure accuracy and completeness
**Quality Standards:**
- Documentation matches actual code behavior
- Examples are runnable and correct
- All public APIs documented
- Clear and concise language
- Proper formatting and structure
**Output Format:**
Create documentation in project's standard format:
- Function/method signatures
- Description of behavior
- Parameters with types and descriptions
- Return values
- Exceptions/errors
- Usage examples
- Notes or warnings if applicable
**Edge Cases:**
- Private/internal code: Document only if requested
- Complex APIs: Break into sections, provide multiple examples
- Deprecated code: Mark as deprecated with migration guide
- Unclear behavior: Document observable behavior, note assumptions
```
## Example 4: Security Analyzer
**File:** `agents/security-analyzer.md`
```markdown
---
name: security-analyzer
description: Use this agent when the user implements security-critical code (auth, payments, data handling), explicitly requests security analysis, or before deploying sensitive changes. Examples:
<example>
Context: User implemented authentication logic
user: "I've added JWT token validation"
assistant: "Let me check the security."
<commentary>
Authentication code is security-critical. Proactively trigger security-analyzer.
</commentary>
assistant: "I'll use the security-analyzer agent to review for security vulnerabilities."
</example>
<example>
Context: User requests security check
user: "Check my code for security issues"
assistant: "I'll use the security-analyzer agent to perform a thorough security review."
<commentary>
Explicit security review request triggers the agent.
</commentary>
</example>
model: inherit
color: red
tools: ["Read", "Grep", "Glob"]
---
You are an expert security analyst specializing in identifying vulnerabilities and security issues in software implementations.
**Your Core Responsibilities:**
1. Identify security vulnerabilities (OWASP Top 10 and beyond)
2. Analyze authentication and authorization logic
3. Check input validation and sanitization
4. Verify secure data handling and storage
5. Provide specific remediation guidance
**Security Analysis Process:**
1. **Identify Attack Surface**: Find user input points, APIs, database queries
2. **Check Common Vulnerabilities**:
- Injection (SQL, command, XSS, etc.)
- Authentication/authorization flaws
- Sensitive data exposure
- Security misconfiguration
- Insecure deserialization
3. **Analyze Patterns**:
- Input validation at boundaries
- Output encoding
- Parameterized queries
- Principle of least privilege
4. **Assess Risk**: Categorize by severity and exploitability
5. **Provide Remediation**: Specific fixes with examples
**Quality Standards:**
- Every vulnerability includes CVE/CWE reference when applicable
- Severity based on CVSS criteria
- Remediation includes code examples
- False positive rate minimized
**Output Format:**
## Security Analysis Report
### Summary
[High-level security posture assessment]
### Critical Vulnerabilities ([count])
- **[Vulnerability Type]** at `file:line`
- Risk: [Description of security impact]
- How to Exploit: [Attack scenario]
- Fix: [Specific remediation with code example]
### Medium/Low Vulnerabilities
[...]
### Security Best Practices Recommendations
[...]
### Overall Risk Assessment
[High/Medium/Low with justification]
**Edge Cases:**
- No vulnerabilities: Confirm security review completed, mention what was checked
- False positives: Verify before reporting
- Uncertain vulnerabilities: Mark as "potential" with caveat
- Out of scope items: Note but don't deep-dive
```
## Customization Tips
### Adapt to Your Domain
Take these templates and customize:
- Change domain expertise (e.g., "Python expert" vs "React expert")
- Adjust process steps for your specific workflow
- Modify output format to match your needs
- Add domain-specific quality standards
- Include technology-specific checks
### Adjust Tool Access
Restrict or expand based on agent needs:
- **Read-only agents**: `["Read", "Grep", "Glob"]`
- **Generator agents**: `["Read", "Write", "Grep"]`
- **Executor agents**: `["Read", "Write", "Bash", "Grep"]`
- **Full access**: Omit tools field
### Customize Colors
Choose colors that match agent purpose:
- **Blue**: Analysis, review, investigation
- **Cyan**: Documentation, information
- **Green**: Generation, creation, success-oriented
- **Yellow**: Validation, warnings, caution
- **Red**: Security, critical analysis, errors
- **Magenta**: Refactoring, transformation, creative
## Using These Templates
1. Copy template that matches your use case
2. Replace placeholders with your specifics
3. Customize process steps for your domain
4. Adjust examples to your triggering scenarios
5. Validate with `scripts/validate-agent.sh`
6. Test triggering with real scenarios
7. Iterate based on agent performance
These templates provide battle-tested starting points. Customize them for your specific needs while maintaining the proven structure.

View File

@@ -0,0 +1,207 @@
# Agent Creation System Prompt
This is the exact system prompt used by Claude Code's agent generation feature, refined through extensive production use.
## The Prompt
```
You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.
**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.
When a user describes what they want an agent to do, you will:
1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.
2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.
3. **Architect Comprehensive Instructions**: Develop a system prompt that:
- Establishes clear behavioral boundaries and operational parameters
- Provides specific methodologies and best practices for task execution
- Anticipates edge cases and provides guidance for handling them
- Incorporates any specific requirements or preferences mentioned by the user
- Defines output format expectations when relevant
- Aligns with project-specific coding standards and patterns from CLAUDE.md
4. **Optimize for Performance**: Include:
- Decision-making frameworks appropriate to the domain
- Quality control mechanisms and self-verification steps
- Efficient workflow patterns
- Clear escalation or fallback strategies
5. **Create Identifier**: Design a concise, descriptive identifier that:
- Uses lowercase letters, numbers, and hyphens only
- Is typically 2-4 words joined by hyphens
- Clearly indicates the agent's primary function
- Is memorable and easy to type
- Avoids generic terms like "helper" or "assistant"
6. **Example agent descriptions**:
- In the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
- Examples should be of the form:
<example>
Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
user: "Please write a function that checks if a number is prime"
assistant: "Here is the relevant function: "
<function call omitted for brevity only for this example>
<commentary>
Since a logical chunk of code was written and the task was completed, now use the code-review agent to review the code.
</commentary>
assistant: "Now let me use the code-reviewer agent to review the code"
</example>
- If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.
Your output must be a valid JSON object with exactly these fields:
{
"identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')",
"whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
"systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
}
Key principles for your system prompts:
- Be specific rather than generic - avoid vague instructions
- Include concrete examples when they would clarify behavior
- Balance comprehensiveness with clarity - every instruction should add value
- Ensure the agent has enough context to handle variations of the core task
- Make the agent proactive in seeking clarification when needed
- Build in quality assurance and self-correction mechanisms
Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
```
## Usage Pattern
Use this prompt to generate agent configurations:
```markdown
**User input:** "I need an agent that reviews pull requests for code quality issues"
**You send to Claude with the system prompt above:**
Create an agent configuration based on this request: "I need an agent that reviews pull requests for code quality issues"
**Claude returns JSON:**
{
"identifier": "pr-quality-reviewer",
"whenToUse": "Use this agent when the user asks to review a pull request, check code quality, or analyze PR changes. Examples:\n\n<example>\nContext: User has created a PR and wants quality review\nuser: \"Can you review PR #123 for code quality?\"\nassistant: \"I'll use the pr-quality-reviewer agent to analyze the PR.\"\n<commentary>\nPR review request triggers the pr-quality-reviewer agent.\n</commentary>\n</example>",
"systemPrompt": "You are an expert code quality reviewer...\n\n**Your Core Responsibilities:**\n1. Analyze code changes for quality issues\n2. Check adherence to best practices\n..."
}
```
## Converting to Agent File
Take the JSON output and create the agent markdown file:
**agents/pr-quality-reviewer.md:**
```markdown
---
name: pr-quality-reviewer
description: Use this agent when the user asks to review a pull request, check code quality, or analyze PR changes. Examples:
<example>
Context: User has created a PR and wants quality review
user: "Can you review PR #123 for code quality?"
assistant: "I'll use the pr-quality-reviewer agent to analyze the PR."
<commentary>
PR review request triggers the pr-quality-reviewer agent.
</commentary>
</example>
model: inherit
color: blue
---
You are an expert code quality reviewer...
**Your Core Responsibilities:**
1. Analyze code changes for quality issues
2. Check adherence to best practices
...
```
## Customization Tips
### Adapt the System Prompt
The base prompt is excellent but can be enhanced for specific needs:
**For security-focused agents:**
```
Add after "Architect Comprehensive Instructions":
- Include OWASP top 10 security considerations
- Check for common vulnerabilities (injection, XSS, etc.)
- Validate input sanitization
```
**For test-generation agents:**
```
Add after "Optimize for Performance":
- Follow AAA pattern (Arrange, Act, Assert)
- Include edge cases and error scenarios
- Ensure test isolation and cleanup
```
**For documentation agents:**
```
Add after "Design Expert Persona":
- Use clear, concise language
- Include code examples
- Follow project documentation standards from CLAUDE.md
```
## Best Practices from Internal Implementation
### 1. Consider Project Context
The prompt specifically mentions using CLAUDE.md context:
- Agent should align with project patterns
- Follow project-specific coding standards
- Respect established practices
### 2. Proactive Agent Design
Include examples showing proactive usage:
```
<example>
Context: After writing code, agent should review proactively
user: "Please write a function..."
assistant: "[Writes function]"
<commentary>
Code written, now use review agent proactively.
</commentary>
assistant: "Now let me review this code with the code-reviewer agent"
</example>
```
### 3. Scope Assumptions
For code review agents, assume "recently written code" not entire codebase:
```
For agents that review code, assume recent changes unless explicitly
stated otherwise.
```
### 4. Output Structure
Always define clear output format in system prompt:
```
**Output Format:**
Provide results as:
1. Summary (2-3 sentences)
2. Detailed findings (bullet points)
3. Recommendations (action items)
```
## Integration with Plugin-Dev
Use this system prompt when creating agents for your plugins:
1. Take user request for agent functionality
2. Feed to Claude with this system prompt
3. Get JSON output (identifier, whenToUse, systemPrompt)
4. Convert to agent markdown file with frontmatter
5. Validate with agent validation rules
6. Test triggering conditions
7. Add to plugin's `agents/` directory
This provides AI-assisted agent generation following proven patterns from Claude Code's internal implementation.

View File

@@ -0,0 +1,411 @@
# System Prompt Design Patterns
Complete guide to writing effective agent system prompts that enable autonomous, high-quality operation.
## Core Structure
Every agent system prompt should follow this proven structure:
```markdown
You are [specific role] specializing in [specific domain].
**Your Core Responsibilities:**
1. [Primary responsibility - the main task]
2. [Secondary responsibility - supporting task]
3. [Additional responsibilities as needed]
**[Task Name] Process:**
1. [First concrete step]
2. [Second concrete step]
3. [Continue with clear steps]
[...]
**Quality Standards:**
- [Standard 1 with specifics]
- [Standard 2 with specifics]
- [Standard 3 with specifics]
**Output Format:**
Provide results structured as:
- [Component 1]
- [Component 2]
- [Include specific formatting requirements]
**Edge Cases:**
Handle these situations:
- [Edge case 1]: [Specific handling approach]
- [Edge case 2]: [Specific handling approach]
```
## Pattern 1: Analysis Agents
For agents that analyze code, PRs, or documentation:
```markdown
You are an expert [domain] analyzer specializing in [specific analysis type].
**Your Core Responsibilities:**
1. Thoroughly analyze [what] for [specific issues]
2. Identify [patterns/problems/opportunities]
3. Provide actionable recommendations
**Analysis Process:**
1. **Gather Context**: Read [what] using available tools
2. **Initial Scan**: Identify obvious [issues/patterns]
3. **Deep Analysis**: Examine [specific aspects]:
- [Aspect 1]: Check for [criteria]
- [Aspect 2]: Verify [criteria]
- [Aspect 3]: Assess [criteria]
4. **Synthesize Findings**: Group related issues
5. **Prioritize**: Rank by [severity/impact/urgency]
6. **Generate Report**: Format according to output template
**Quality Standards:**
- Every finding includes file:line reference
- Issues categorized by severity (critical/major/minor)
- Recommendations are specific and actionable
- Positive observations included for balance
**Output Format:**
## Summary
[2-3 sentence overview]
## Critical Issues
- [file:line] - [Issue description] - [Recommendation]
## Major Issues
[...]
## Minor Issues
[...]
## Recommendations
[...]
**Edge Cases:**
- No issues found: Provide positive feedback and validation
- Too many issues: Group and prioritize top 10
- Unclear code: Request clarification rather than guessing
```
## Pattern 2: Generation Agents
For agents that create code, tests, or documentation:
```markdown
You are an expert [domain] engineer specializing in creating high-quality [output type].
**Your Core Responsibilities:**
1. Generate [what] that meets [quality standards]
2. Follow [specific conventions/patterns]
3. Ensure [correctness/completeness/clarity]
**Generation Process:**
1. **Understand Requirements**: Analyze what needs to be created
2. **Gather Context**: Read existing [code/docs/tests] for patterns
3. **Design Structure**: Plan [architecture/organization/flow]
4. **Generate Content**: Create [output] following:
- [Convention 1]
- [Convention 2]
- [Best practice 1]
5. **Validate**: Verify [correctness/completeness]
6. **Document**: Add comments/explanations as needed
**Quality Standards:**
- Follows project conventions (check CLAUDE.md)
- [Specific quality metric 1]
- [Specific quality metric 2]
- Includes error handling
- Well-documented and clear
**Output Format:**
Create [what] with:
- [Structure requirement 1]
- [Structure requirement 2]
- Clear, descriptive naming
- Comprehensive coverage
**Edge Cases:**
- Insufficient context: Ask user for clarification
- Conflicting patterns: Follow most recent/explicit pattern
- Complex requirements: Break into smaller pieces
```
## Pattern 3: Validation Agents
For agents that validate, check, or verify:
```markdown
You are an expert [domain] validator specializing in ensuring [quality aspect].
**Your Core Responsibilities:**
1. Validate [what] against [criteria]
2. Identify violations and issues
3. Provide clear pass/fail determination
**Validation Process:**
1. **Load Criteria**: Understand validation requirements
2. **Scan Target**: Read [what] needs validation
3. **Check Rules**: For each rule:
- [Rule 1]: [Validation method]
- [Rule 2]: [Validation method]
4. **Collect Violations**: Document each failure with details
5. **Assess Severity**: Categorize issues
6. **Determine Result**: Pass only if [criteria met]
**Quality Standards:**
- All violations include specific locations
- Severity clearly indicated
- Fix suggestions provided
- No false positives
**Output Format:**
## Validation Result: [PASS/FAIL]
## Summary
[Overall assessment]
## Violations Found: [count]
### Critical ([count])
- [Location]: [Issue] - [Fix]
### Warnings ([count])
- [Location]: [Issue] - [Fix]
## Recommendations
[How to fix violations]
**Edge Cases:**
- No violations: Confirm validation passed
- Too many violations: Group by type, show top 20
- Ambiguous rules: Document uncertainty, request clarification
```
## Pattern 4: Orchestration Agents
For agents that coordinate multiple tools or steps:
```markdown
You are an expert [domain] orchestrator specializing in coordinating [complex workflow].
**Your Core Responsibilities:**
1. Coordinate [multi-step process]
2. Manage [resources/tools/dependencies]
3. Ensure [successful completion/integration]
**Orchestration Process:**
1. **Plan**: Understand full workflow and dependencies
2. **Prepare**: Set up prerequisites
3. **Execute Phases**:
- Phase 1: [What] using [tools]
- Phase 2: [What] using [tools]
- Phase 3: [What] using [tools]
4. **Monitor**: Track progress and handle failures
5. **Verify**: Confirm successful completion
6. **Report**: Provide comprehensive summary
**Quality Standards:**
- Each phase completes successfully
- Errors handled gracefully
- Progress reported to user
- Final state verified
**Output Format:**
## Workflow Execution Report
### Completed Phases
- [Phase]: [Result]
### Results
- [Output 1]
- [Output 2]
### Next Steps
[If applicable]
**Edge Cases:**
- Phase failure: Attempt retry, then report and stop
- Missing dependencies: Request from user
- Timeout: Report partial completion
```
## Writing Style Guidelines
### Tone and Voice
**Use second person (addressing the agent):**
```
✅ You are responsible for...
✅ You will analyze...
✅ Your process should...
❌ The agent is responsible for...
❌ This agent will analyze...
❌ I will analyze...
```
### Clarity and Specificity
**Be specific, not vague:**
```
✅ Check for SQL injection by examining all database queries for parameterization
❌ Look for security issues
✅ Provide file:line references for each finding
❌ Show where issues are
✅ Categorize as critical (security), major (bugs), or minor (style)
❌ Rate the severity of issues
```
### Actionable Instructions
**Give concrete steps:**
```
✅ Read the file using the Read tool, then search for patterns using Grep
❌ Analyze the code
✅ Generate test file at test/path/to/file.test.ts
❌ Create tests
```
## Common Pitfalls
### ❌ Vague Responsibilities
```markdown
**Your Core Responsibilities:**
1. Help the user with their code
2. Provide assistance
3. Be helpful
```
**Why bad:** Not specific enough to guide behavior.
### ✅ Specific Responsibilities
```markdown
**Your Core Responsibilities:**
1. Analyze TypeScript code for type safety issues
2. Identify missing type annotations and improper 'any' usage
3. Recommend specific type improvements with examples
```
### ❌ Missing Process Steps
```markdown
Analyze the code and provide feedback.
```
**Why bad:** Agent doesn't know HOW to analyze.
### ✅ Clear Process
```markdown
**Analysis Process:**
1. Read code files using Read tool
2. Scan for type annotations on all functions
3. Check for 'any' type usage
4. Verify generic type parameters
5. List findings with file:line references
```
### ❌ Undefined Output
```markdown
Provide a report.
```
**Why bad:** Agent doesn't know what format to use.
### ✅ Defined Output Format
```markdown
**Output Format:**
## Type Safety Report
### Summary
[Overview of findings]
### Issues Found
- `file.ts:42` - Missing return type on `processData`
- `utils.ts:15` - Unsafe 'any' usage in parameter
### Recommendations
[Specific fixes with examples]
```
## Length Guidelines
### Minimum Viable Agent
**~500 words minimum:**
- Role description
- 3 core responsibilities
- 5-step process
- Output format
### Standard Agent
**~1,000-2,000 words:**
- Detailed role and expertise
- 5-8 responsibilities
- 8-12 process steps
- Quality standards
- Output format
- 3-5 edge cases
### Comprehensive Agent
**~2,000-5,000 words:**
- Complete role with background
- Comprehensive responsibilities
- Detailed multi-phase process
- Extensive quality standards
- Multiple output formats
- Many edge cases
- Examples within system prompt
**Avoid > 10,000 words:** Too long, diminishing returns.
## Testing System Prompts
### Test Completeness
Can the agent handle these based on system prompt alone?
- [ ] Typical task execution
- [ ] Edge cases mentioned
- [ ] Error scenarios
- [ ] Unclear requirements
- [ ] Large/complex inputs
- [ ] Empty/missing inputs
### Test Clarity
Read the system prompt and ask:
- Can another developer understand what this agent does?
- Are process steps clear and actionable?
- Is output format unambiguous?
- Are quality standards measurable?
### Iterate Based on Results
After testing agent:
1. Identify where it struggled
2. Add missing guidance to system prompt
3. Clarify ambiguous instructions
4. Add process steps for edge cases
5. Re-test
## Conclusion
Effective system prompts are:
- **Specific**: Clear about what and how
- **Structured**: Organized with clear sections
- **Complete**: Covers normal and edge cases
- **Actionable**: Provides concrete steps
- **Testable**: Defines measurable standards
Use the patterns above as templates, customize for your domain, and iterate based on agent performance.

View File

@@ -0,0 +1,491 @@
# Agent Triggering Examples: Best Practices
Complete guide to writing effective `<example>` blocks in agent descriptions for reliable triggering.
## Example Block Format
The standard format for triggering examples:
```markdown
<example>
Context: [Describe the situation - what led to this interaction]
user: "[Exact user message or request]"
assistant: "[How Claude should respond before triggering]"
<commentary>
[Explanation of why this agent should be triggered in this scenario]
</commentary>
assistant: "[How Claude triggers the agent - usually 'I'll use the [agent-name] agent...']"
</example>
```
## Anatomy of a Good Example
### Context
**Purpose:** Set the scene - what happened before the user's message
**Good contexts:**
```
Context: User just implemented a new authentication feature
Context: User has created a PR and wants it reviewed
Context: User is debugging a test failure
Context: After writing several functions without documentation
```
**Bad contexts:**
```
Context: User needs help (too vague)
Context: Normal usage (not specific)
```
### User Message
**Purpose:** Show the exact phrasing that should trigger the agent
**Good user messages:**
```
user: "I've added the OAuth flow, can you check it?"
user: "Review PR #123"
user: "Why is this test failing?"
user: "Add docs for these functions"
```
**Vary the phrasing:**
Include multiple examples with different phrasings for the same intent:
```
Example 1: user: "Review my code"
Example 2: user: "Can you check this implementation?"
Example 3: user: "Look over my changes"
```
### Assistant Response (Before Triggering)
**Purpose:** Show what Claude says before launching the agent
**Good responses:**
```
assistant: "I'll analyze your OAuth implementation."
assistant: "Let me review that PR for you."
assistant: "I'll investigate the test failure."
```
**Proactive example:**
```
assistant: "Great! Now let me review the code quality."
<commentary>
Code was just written, proactively trigger review agent.
</commentary>
```
### Commentary
**Purpose:** Explain the reasoning - WHY this agent should trigger
**Good commentary:**
```
<commentary>
User explicitly requested code review, trigger the code-reviewer agent.
</commentary>
<commentary>
After code implementation, proactively use review agent to check quality.
</commentary>
<commentary>
PR analysis request matches pr-analyzer agent's expertise.
</commentary>
```
**Include decision logic:**
```
<commentary>
User wrote tests (Test tool used). The test-analyzer agent should check
test quality and coverage before continuing.
</commentary>
```
### Assistant Response (Triggering)
**Purpose:** Show how Claude invokes the agent
**Standard pattern:**
```
assistant: "I'll use the [agent-name] agent to [what it will do]."
```
**Examples:**
```
assistant: "I'll use the code-reviewer agent to analyze the changes."
assistant: "Let me use the test-generator agent to create comprehensive tests."
assistant: "I'll use the security-analyzer agent to check for vulnerabilities."
```
## Example Types
### Type 1: Explicit Request
User directly asks for what the agent does:
```markdown
<example>
Context: User explicitly requests security analysis
user: "Check my code for security vulnerabilities"
assistant: "I'll use the security-analyzer agent to perform a thorough security review."
<commentary>
Direct security analysis request triggers the security-analyzer agent.
</commentary>
</example>
```
### Type 2: Proactive Triggering
Agent triggers after relevant work without explicit request:
```markdown
<example>
Context: User just implemented database queries
user: "I've added the user search functionality"
assistant: "Great! Let me review it for security."
<commentary>
Database code written. Proactively trigger security-analyzer to check
for SQL injection and other database security issues.
</commentary>
assistant: "I'll use the security-analyzer agent to check the database code."
</example>
```
### Type 3: Implicit Request
User implies need without stating it directly:
```markdown
<example>
Context: User mentions code is hard to understand
user: "This code is confusing and hard to follow"
assistant: "I can help improve the code clarity."
<commentary>
User indicates complexity issues. Trigger code-simplifier agent to refactor
for better readability.
</commentary>
assistant: "I'll use the code-simplifier agent to suggest improvements."
</example>
```
### Type 4: Tool Usage Pattern
Agent triggers based on prior tool usage:
```markdown
<example>
Context: User made multiple edits to test files
user: "I've updated all the tests"
assistant: "Great! Let me verify test quality."
<commentary>
Multiple Edit tools used on test files. Proactively trigger test-quality-analyzer
to ensure tests follow best practices.
</commentary>
assistant: "I'll use the test-quality-analyzer agent to review the tests."
</example>
```
## Multiple Examples Strategy
### Cover Different Phrasings
```markdown
<example>
user: "Review my code"
[...]
</example>
<example>
user: "Can you check my implementation?"
[...]
</example>
<example>
user: "Look over these changes"
[...]
</example>
```
### Cover Proactive and Reactive
```markdown
<example>
Context: User explicitly requests review
user: "Review my code for issues"
[...]
</example>
<example>
Context: After user writes code
user: "I've implemented the feature"
assistant: "Great! Now let me review it."
<commentary>
Code written, proactively review.
</commentary>
[...]
</example>
```
### Cover Edge Cases
```markdown
<example>
Context: Typical usage
user: "Check my PR"
[...]
</example>
<example>
Context: Large PR that needs thorough analysis
user: "This is a big PR, can you do a deep review?"
[...]
<commentary>
Large PR mentioned, use thorough analysis mode.
</commentary>
</example>
```
## Common Mistakes
### ❌ Missing Context
```markdown
<example>
user: "Review my code"
assistant: "I'll use the code-reviewer agent."
</example>
```
**Why bad:** No context about what led to this request.
### ✅ With Context
```markdown
<example>
Context: User just finished implementing authentication
user: "Review my code"
assistant: "I'll use the code-reviewer agent to analyze the auth implementation."
<commentary>
Auth code written, review for security and best practices.
</commentary>
</example>
```
### ❌ No Commentary
```markdown
<example>
Context: User requests review
user: "Check my changes"
assistant: "I'll use the reviewer agent."
</example>
```
**Why bad:** Doesn't explain WHY agent triggers.
### ✅ With Commentary
```markdown
<example>
Context: User requests review after making changes
user: "Check my changes"
assistant: "I'll use the code-reviewer agent to analyze the modifications."
<commentary>
Code review request triggers agent to check quality, security, and adherence to standards.
</commentary>
</example>
```
### ❌ Agent Responds Directly
```markdown
<example>
user: "Review my code"
assistant: "I found the following issues: [lists issues]"
</example>
```
**Why bad:** Shows agent's output, not triggering.
### ✅ Shows Triggering
```markdown
<example>
user: "Review my code"
assistant: "I'll use the code-reviewer agent to perform the review."
<commentary>
Review request triggers the agent.
</commentary>
</example>
```
## How Many Examples?
### Minimum: 2 Examples
Cover at least:
1. Explicit request
2. One variation or proactive trigger
### Recommended: 3-4 Examples
Cover:
1. Explicit request (direct ask)
2. Implicit request (user implies need)
3. Proactive trigger (after relevant work)
4. Edge case or specific scenario
### Maximum: 6 Examples
More than 6 makes description too long. Focus on most important scenarios.
## Template Library
### Code Review Agent
```markdown
<example>
Context: User just implemented a new feature
user: "I've added the user registration feature"
assistant: "Great! Let me review the code quality."
<commentary>
Code written, proactively trigger code-reviewer agent.
</commentary>
assistant: "I'll use the code-reviewer agent to analyze the implementation."
</example>
<example>
Context: User explicitly requests review
user: "Can you review my changes for issues?"
assistant: "I'll use the code-reviewer agent to perform a thorough review."
<commentary>
Explicit review request triggers the agent.
</commentary>
</example>
```
### Test Generation Agent
```markdown
<example>
Context: User implemented functions without tests
user: "I've added the data processing functions"
assistant: "Great! Let me generate tests for these."
<commentary>
New code without tests, proactively trigger test-generator agent.
</commentary>
assistant: "I'll use the test-generator agent to create comprehensive tests."
</example>
<example>
Context: User explicitly asks for tests
user: "Generate tests for my code"
assistant: "I'll use the test-generator agent to create a complete test suite."
<commentary>
Direct test generation request triggers the agent.
</commentary>
</example>
```
### Documentation Agent
```markdown
<example>
Context: User added new API endpoints
user: "I've implemented the REST API endpoints"
assistant: "I'll document these endpoints."
<commentary>
New API code, proactively generate documentation.
</commentary>
assistant: "I'll use the api-docs-writer agent to create comprehensive documentation."
</example>
<example>
Context: User requests documentation
user: "Write docs for this API"
assistant: "I'll use the api-docs-writer agent to generate clear documentation."
<commentary>
Documentation request triggers the agent.
</commentary>
</example>
```
### Validation Agent
```markdown
<example>
Context: User ready to commit changes
user: "I'm ready to commit this code"
assistant: "Let me validate it first."
<commentary>
Before commit, proactively validate with validation-agent.
</commentary>
assistant: "I'll use the code-validator agent to check for issues."
</example>
<example>
Context: User asks for validation
user: "Validate my implementation"
assistant: "I'll use the code-validator agent to verify correctness."
<commentary>
Explicit validation request triggers the agent.
</commentary>
</example>
```
## Debugging Triggering Issues
### Agent Not Triggering
**Check:**
1. Examples include relevant keywords from user message
2. Context matches actual usage scenarios
3. Commentary explains triggering logic clearly
4. Assistant shows use of Agent tool in examples
**Fix:**
Add more examples covering different phrasings.
### Agent Triggers Too Often
**Check:**
1. Examples are too broad or generic
2. Triggering conditions overlap with other agents
3. Commentary doesn't distinguish when NOT to use
**Fix:**
Make examples more specific, add negative examples.
### Agent Triggers in Wrong Scenarios
**Check:**
1. Examples don't match actual intended use
2. Commentary suggests inappropriate triggering
**Fix:**
Revise examples to show only correct triggering scenarios.
## Best Practices Summary
**DO:**
- Include 2-4 concrete, specific examples
- Show both explicit and proactive triggering
- Provide clear context for each example
- Explain reasoning in commentary
- Vary user message phrasing
- Show Claude using Agent tool
**DON'T:**
- Use generic, vague examples
- Omit context or commentary
- Show only one type of triggering
- Skip the agent invocation step
- Make examples too similar
- Forget to explain why agent triggers
## Conclusion
Well-crafted examples are crucial for reliable agent triggering. Invest time in creating diverse, specific examples that clearly demonstrate when and why the agent should be used.

View File

@@ -0,0 +1,217 @@
#!/bin/bash
# Agent File Validator
# Validates agent markdown files for correct structure and content
set -euo pipefail
# Usage
if [ $# -eq 0 ]; then
echo "Usage: $0 <path/to/agent.md>"
echo ""
echo "Validates agent file for:"
echo " - YAML frontmatter structure"
echo " - Required fields (name, description, model, color)"
echo " - Field formats and constraints"
echo " - System prompt presence and length"
echo " - Example blocks in description"
exit 1
fi
AGENT_FILE="$1"
echo "🔍 Validating agent file: $AGENT_FILE"
echo ""
# Check 1: File exists
if [ ! -f "$AGENT_FILE" ]; then
echo "❌ File not found: $AGENT_FILE"
exit 1
fi
echo "✅ File exists"
# Check 2: Starts with ---
FIRST_LINE=$(head -1 "$AGENT_FILE")
if [ "$FIRST_LINE" != "---" ]; then
echo "❌ File must start with YAML frontmatter (---)"
exit 1
fi
echo "✅ Starts with frontmatter"
# Check 3: Has closing ---
if ! tail -n +2 "$AGENT_FILE" | grep -q '^---$'; then
echo "❌ Frontmatter not closed (missing second ---)"
exit 1
fi
echo "✅ Frontmatter properly closed"
# Extract frontmatter and system prompt
FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$AGENT_FILE")
SYSTEM_PROMPT=$(awk '/^---$/{i++; next} i>=2' "$AGENT_FILE")
# Check 4: Required fields
echo ""
echo "Checking required fields..."
error_count=0
warning_count=0
# Check name field
NAME=$(echo "$FRONTMATTER" | grep '^name:' | sed 's/name: *//' | sed 's/^"\(.*\)"$/\1/')
if [ -z "$NAME" ]; then
echo "❌ Missing required field: name"
((error_count++))
else
echo "✅ name: $NAME"
# Validate name format
if ! [[ "$NAME" =~ ^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$ ]]; then
echo "❌ name must start/end with alphanumeric and contain only letters, numbers, hyphens"
((error_count++))
fi
# Validate name length
name_length=${#NAME}
if [ $name_length -lt 3 ]; then
echo "❌ name too short (minimum 3 characters)"
((error_count++))
elif [ $name_length -gt 50 ]; then
echo "❌ name too long (maximum 50 characters)"
((error_count++))
fi
# Check for generic names
if [[ "$NAME" =~ ^(helper|assistant|agent|tool)$ ]]; then
echo "⚠️ name is too generic: $NAME"
((warning_count++))
fi
fi
# Check description field
DESCRIPTION=$(echo "$FRONTMATTER" | grep '^description:' | sed 's/description: *//')
if [ -z "$DESCRIPTION" ]; then
echo "❌ Missing required field: description"
((error_count++))
else
desc_length=${#DESCRIPTION}
echo "✅ description: ${desc_length} characters"
if [ $desc_length -lt 10 ]; then
echo "⚠️ description too short (minimum 10 characters recommended)"
((warning_count++))
elif [ $desc_length -gt 5000 ]; then
echo "⚠️ description very long (over 5000 characters)"
((warning_count++))
fi
# Check for example blocks
if ! echo "$DESCRIPTION" | grep -q '<example>'; then
echo "⚠️ description should include <example> blocks for triggering"
((warning_count++))
fi
# Check for "Use this agent when" pattern
if ! echo "$DESCRIPTION" | grep -qi 'use this agent when'; then
echo "⚠️ description should start with 'Use this agent when...'"
((warning_count++))
fi
fi
# Check model field
MODEL=$(echo "$FRONTMATTER" | grep '^model:' | sed 's/model: *//')
if [ -z "$MODEL" ]; then
echo "❌ Missing required field: model"
((error_count++))
else
echo "✅ model: $MODEL"
case "$MODEL" in
inherit|sonnet|opus|haiku)
# Valid model
;;
*)
echo "⚠️ Unknown model: $MODEL (valid: inherit, sonnet, opus, haiku)"
((warning_count++))
;;
esac
fi
# Check color field
COLOR=$(echo "$FRONTMATTER" | grep '^color:' | sed 's/color: *//')
if [ -z "$COLOR" ]; then
echo "❌ Missing required field: color"
((error_count++))
else
echo "✅ color: $COLOR"
case "$COLOR" in
blue|cyan|green|yellow|magenta|red)
# Valid color
;;
*)
echo "⚠️ Unknown color: $COLOR (valid: blue, cyan, green, yellow, magenta, red)"
((warning_count++))
;;
esac
fi
# Check tools field (optional)
TOOLS=$(echo "$FRONTMATTER" | grep '^tools:' | sed 's/tools: *//')
if [ -n "$TOOLS" ]; then
echo "✅ tools: $TOOLS"
else
echo "💡 tools: not specified (agent has access to all tools)"
fi
# Check 5: System prompt
echo ""
echo "Checking system prompt..."
if [ -z "$SYSTEM_PROMPT" ]; then
echo "❌ System prompt is empty"
((error_count++))
else
prompt_length=${#SYSTEM_PROMPT}
echo "✅ System prompt: $prompt_length characters"
if [ $prompt_length -lt 20 ]; then
echo "❌ System prompt too short (minimum 20 characters)"
((error_count++))
elif [ $prompt_length -gt 10000 ]; then
echo "⚠️ System prompt very long (over 10,000 characters)"
((warning_count++))
fi
# Check for second person
if ! echo "$SYSTEM_PROMPT" | grep -q "You are\|You will\|Your"; then
echo "⚠️ System prompt should use second person (You are..., You will...)"
((warning_count++))
fi
# Check for structure
if ! echo "$SYSTEM_PROMPT" | grep -qi "responsibilities\|process\|steps"; then
echo "💡 Consider adding clear responsibilities or process steps"
fi
if ! echo "$SYSTEM_PROMPT" | grep -qi "output"; then
echo "💡 Consider defining output format expectations"
fi
fi
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $error_count -eq 0 ] && [ $warning_count -eq 0 ]; then
echo "✅ All checks passed!"
exit 0
elif [ $error_count -eq 0 ]; then
echo "⚠️ Validation passed with $warning_count warning(s)"
exit 0
else
echo "❌ Validation failed with $error_count error(s) and $warning_count warning(s)"
exit 1
fi

View File

@@ -0,0 +1,274 @@
---
name: architecture-design
description: Use only when creating new registrable ML components that require Factory or Registry patterns.
version: 1.2.0
---
# Architecture Design - ML Project Template
This skill defines the standard code architecture for machine learning projects based on the template structure. When modifying or extending code, follow these patterns to maintain consistency.
## Overview
The project follows a modular, extensible architecture with clear separation of concerns. Each module (data, model, trainer, analysis) is independently organized using factory and registry patterns for maximum flexibility.
## When to Use
Use this skill when:
- Creating a new Dataset class that needs `@register_dataset`
- Creating a new Model class that needs `@register_model`
- Creating a new module directory with `__init__.py` factory wiring
- Initializing a new ML project structure from scratch
- Adding new component types such as Augmentation, CollateFunction, or Metrics
## When Not to Use
Do not use this skill when:
- Modifying existing functions or methods
- Fixing bugs in existing code
- Adding helper functions or utilities
- Refactoring without adding new registrable components
- Making simple code changes to a single file
- Modifying configuration files
- Reading or understanding existing code
Key indicator: if the task does not require a `@register_*` decorator or a Factory pattern, skip this skill.
## Core Design Patterns
### Factory Pattern
Each module uses a factory to create instances dynamically:
```python
# Example from data_module/dataset/__init__.py
DATASET_FACTORY: Dict = {}
def DatasetFactory(data_name: str):
dataset = DATASET_FACTORY.get(data_name, None)
if dataset is None:
print(f"{data_name} dataset is not implementation, use simple dataset")
dataset = DATASET_FACTORY.get('simple')
return dataset
```
For detailed guidance, refer to `references/factory_pattern.md`.
### Registry Pattern
Components register themselves via decorators:
```python
# Example from data_module/dataset/simple_dataset.py
@register_dataset("simple")
class SimpleDataset(Dataset):
def __init__(self, data):
self.data = data
```
For detailed guidance, refer to `references/registry_pattern.md`.
### Auto-Import Pattern
Modules automatically discover and import submodules:
```python
# Example from data_module/dataset/__init__.py
models_dir = os.path.dirname(__file__)
import_modules(models_dir, "src.data_module.dataset")
```
For detailed guidance, refer to `references/auto_import.md`.
## Directory Structure
```
project/
├── run/
│ ├── pipeline/ # Main workflow scripts
│ │ ├── training/ # Training pipelines
│ │ ├── prepare_data/ # Data preparation pipelines
│ │ └── analysis/ # Analysis pipelines
│ └── conf/ # Hydra configuration files
│ ├── training/ # Training configs
│ ├── dataset/ # Dataset configs
│ ├── model/ # Model configs
│ ├── prepare_data/ # Data prep configs
│ └── analysis/ # Analysis configs
├── src/
│ ├── data_module/ # Data processing module
│ │ ├── dataset/ # Dataset implementations
│ │ ├── augmentation/ # Data augmentation
│ │ ├── collate_fn/ # Collate functions
│ │ ├── compute_metrics/ # Metrics computation
│ │ ├── prepare_data/ # Data preparation logic
│ │ ├── data_func/ # Data utility functions
│ │ └── utils.py # Module-specific utilities
│ │
│ ├── model_module/ # Model implementations
│ │ ├── brain_decoder/ # Brain decoder models
│ │ └── model/ # Alternative model location
│ │
│ ├── trainer_module/ # Training logic
│ ├── analysis_module/ # Analysis and evaluation
│ ├── llm/ # LLM-related code
│ └── utils/ # Shared utilities
├── data/
│ ├── raw/ # Original, immutable data
│ ├── processed/ # Cleaned, transformed data
│ └── external/ # Third-party data
├── outputs/
│ ├── logs/ # Training and evaluation logs
│ ├── checkpoints/ # Model checkpoints
│ ├── tables/ # Result tables
│ └── figures/ # Plots and visualizations
├── pyproject.toml # Project configuration
├── uv.lock # Dependency lock file
├── TODO.md # Task tracking
├── README.md # Project documentation
└── .gitignore # Git ignore rules
```
For detailed directory structure with file descriptions, refer to `references/structure.md`.
## Module Organization
### Creating a New Dataset
When adding a new dataset:
1. Create file in `src/data_module/dataset/`
2. Use `@register_dataset("name")` decorator
3. Inherit from `torch.utils.data.Dataset`
4. Implement `__init__`, `__len__`, `__getitem__`
```python
from torch.utils.data import Dataset
from typing import Dict
import torch
from src.data_module.dataset import register_dataset
@register_dataset("custom")
class CustomDataset(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
def __getitem__(self, i: int) -> Dict[str, torch.Tensor]:
return self.data[i]
```
### Creating a New Model
**CRITICAL: Models use config-driven pattern**
When adding a new model:
1. Create file in `src/model_module/model/` or appropriate module subdirectory
2. Use `@register_model('ModelName')` decorator
3. `__init__` accepts **ONLY** `cfg` parameter - all hyperparameters come from config
4. `forward()` returns dict: `{"loss": loss, "labels": labels, "logits": logits}`
5. Handle training vs inference modes using `self.training`
```python
from src.model_module.brain_decoder import register_model
@register_model('MyModel')
class MyModel(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.task = cfg.dataset.task
# ALL parameters from cfg
self.hidden_dim = cfg.model.hidden_dim
self.output_dim = cfg.dataset.target_size[cfg.dataset.task]
def forward(self, x, labels=None, **kwargs):
if self.training:
# Training logic
pass
else:
# Inference logic
pass
return {"loss": loss, "labels": labels, "logits": logits}
```
### Adding Data Augmentation
When adding augmentation:
1. Create file in `src/data_module/augmentation/`
2. Implement transformation function
3. Register with factory if needed
## Code Style Guidelines
For comprehensive style guidelines, refer to `references/code_style.md`.
**Key principles:**
- Always use type hints for function signatures
- Follow import order: standard library → third-party → local
- Module `__init__.py` files contain factory/registry logic
- Model classes must be config-driven
## Configuration Management
The project uses Hydra for configuration management:
- Config files in `run/conf/` organize by module
- Each stage (training, analysis) has its own config structure
- Use YAML files for all configuration
## When Working on This Project
### Before Modifying Code
1. Read the relevant module's factory/registry pattern
2. Check existing implementations for consistency
3. Follow the established directory structure
4. Use registration decorators for new components
### Adding New Features
1. Determine which module the feature belongs to
2. Check if similar functionality exists
3. Follow factory/registry pattern if creating new component types
4. Add configuration files if needed
5. Update documentation
### Code Review Checklist
- [ ] Uses factory/registry pattern appropriately
- [ ] Follows module directory structure
- [ ] Has proper type annotations
- [ ] Imports are correctly ordered
- [ ] Registration decorator is used
- [ ] Configuration files are added if needed
## Additional Resources
### Reference Files
For detailed information, consult:
- **`references/structure.md`** - Detailed directory structure with file descriptions
- **`references/factory_pattern.md`** - Factory pattern in-depth explanation
- **`references/registry_pattern.md`** - Registry pattern in-depth explanation
- **`references/auto_import.md`** - Auto-import pattern in-depth explanation
- **`references/code_style.md`** - Comprehensive code style guidelines
### Example Files
Working examples in `examples/`:
- **`examples/custom_dataset.py`** - Custom dataset implementation
- **`examples/custom_model.py`** - Custom model implementation
- **`examples/augmentation_example.py`** - Data augmentation example
- **`examples/config_example.yaml`** - Configuration file example
- **`examples/pipeline_example.sh`** - Pipeline script example

View File

@@ -0,0 +1,117 @@
"""
Data Augmentation Example
Demonstrates how to create a custom data augmentation function
following the architecture design pattern.
"""
import torch
from typing import Dict
from src.data_module.augmentation import register_augmentation
@register_augmentation("time_shift")
def time_shift(signal: torch.Tensor, max_shift: int = 10) -> torch.Tensor:
"""Randomly shift signal in time.
Args:
signal: Input signal tensor of shape (channels, time_steps)
max_shift: Maximum number of steps to shift
Returns:
Shifted signal tensor
"""
shift = torch.randint(-max_shift, max_shift + 1, (1,)).item()
return torch.roll(signal, shifts=shift, dims=-1)
@register_augmentation("amplitude_scale")
def amplitude_scale(
signal: torch.Tensor,
min_scale: float = 0.8,
max_scale: float = 1.2
) -> torch.Tensor:
"""Randomly scale signal amplitude.
Args:
signal: Input signal tensor of shape (channels, time_steps)
min_scale: Minimum scaling factor
max_scale: Maximum scaling factor
Returns:
Scaled signal tensor
"""
scale = torch.empty(1).uniform_(min_scale, max_scale).item()
return signal * scale
@register_augmentation("gaussian_noise")
def add_gaussian_noise(
signal: torch.Tensor,
mean: float = 0.0,
std: float = 0.1
) -> torch.Tensor:
"""Add Gaussian noise to signal.
Args:
signal: Input signal tensor of shape (channels, time_steps)
mean: Mean of Gaussian noise
std: Standard deviation of Gaussian noise
Returns:
Signal with added noise
"""
noise = torch.randn_like(signal) * std + mean
return signal + noise
# Example: Composed augmentation
@register_augmentation("composed")
def composed_augmentation(signal: torch.Tensor, cfg) -> torch.Tensor:
"""Apply multiple augmentations in sequence.
Args:
signal: Input signal tensor
cfg: Configuration object with augmentation parameters
Returns:
Augmented signal tensor
"""
# Apply each augmentation based on config
if cfg.augmentation.time_shift:
signal = time_shift(signal, cfg.augmentation.max_shift)
if cfg.augmentation.amplitude_scale:
signal = amplitude_scale(
signal,
cfg.augmentation.min_scale,
cfg.augmentation.max_scale
)
if cfg.augmentation.gaussian_noise:
signal = add_gaussian_noise(
signal,
cfg.augmentation.noise_mean,
cfg.augmentation.noise_std
)
return signal
# Usage in dataset class
class AugmentedDataset:
"""Example dataset with augmentation support."""
def __init__(self, cfg):
self.cfg = cfg
self.augmentation_fn = AugmentationFactory(cfg.augmentation.name)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
# Load signal
signal = self.load_signal(idx)
# Apply augmentation (training mode only)
if self.training and self.augmentation_fn:
signal = self.augmentation_fn(signal, self.cfg)
return {"signal": signal, "label": self.labels[idx]}

View File

@@ -0,0 +1,131 @@
# Hydra Configuration Example
# This demonstrates the config structure for training pipeline
# Run with: python train.py --config-name=config_example
defaults:
- training: default
- dataset: brain_decoder
- model: transformer
- override hydra/launcher: submitit_local
# Project settings
project_name: brain_decoder
experiment_name: transformer_baseline
# Random seed
seed: 42
# Device settings
device: cuda
num_workers: 4
pin_memory: true
# Training configuration
training:
epochs: 100
batch_size: 32
learning_rate: 0.001
weight_decay: 0.0001
gradient_clip: 1.0
early_stopping:
patience: 10
min_delta: 0.001
# Optimizer settings
optimizer: adamw
optimizer_params:
betas: [0.9, 0.999]
eps: 1.0e-08
# Scheduler settings
scheduler: cosine
scheduler_params:
warmup_epochs: 10
min_lr: 1.0e-06
# Checkpoint settings
checkpoint:
save_every: 5
save_best: true
monitor: val_loss
mode: min
# Dataset configuration
dataset:
name: brain_decoder
task: movement_classification
target_size:
movement_classification: 5
reconstruction: [64, 64]
# Data paths
data_dir: ${dir.data_dir}/processed
train_split: train
val_split: val
test_split: test
# Data loading
num_channels: 64
sampling_rate: 1000
sequence_length: 1000
# Augmentation
augmentation:
name: composed
time_shift: true
amplitude_scale: true
gaussian_noise: true
max_shift: 10
min_scale: 0.8
max_scale: 1.2
noise_mean: 0.0
noise_std: 0.1
# Model configuration
model:
name: Transformer
hidden_dim: 256
num_heads: 8
num_layers: 6
dropout: 0.1
activation: gelu
# Architecture specific
encoder:
input_dim: 64
embedding_dim: 256
positional_encoding: true
decoder:
output_dim: ${dataset.target_size.${dataset.task}}
pooling: avg
# Logging configuration
logging:
logger: wandb
log_every: 10
log_grads: false
# TensorBoard
tensorboard: true
histogram: true
# W&B
wandb:
project: ${project_name}
entity: null
tags: ["baseline", "transformer"]
# Output directories
dir:
data_dir: ./data
output_dir: ./outputs
log_dir: ${dir.output_dir}/logs
checkpoint_dir: ${dir.output_dir}/checkpoints
figure_dir: ${dir.output_dir}/figures
table_dir: ${dir.output_dir}/tables
# Debug settings
debug: false
fast_dev_run: false

View File

@@ -0,0 +1,50 @@
"""
Example: Creating a Custom Dataset
This example shows how to add a new dataset following the project architecture.
"""
from torch.utils.data import Dataset
from typing import Dict
import torch
from src.data_module.dataset import register_dataset
@register_dataset("time_series")
class TimeSeriesDataset(Dataset):
"""
Time series dataset for sequence modeling.
Args:
sequences: List of time series sequences
seq_length: Fixed sequence length (pad or truncate if needed)
"""
def __init__(self, sequences: list, seq_length: int = 100):
self.sequences = sequences
self.seq_length = seq_length
def __len__(self) -> int:
return len(self.sequences)
def __getitem__(self, i: int) -> Dict[str, torch.Tensor]:
sequence = self.sequences[i]
# Pad or truncate to fixed length
if len(sequence) < self.seq_length:
padding = torch.zeros(self.seq_length - len(sequence))
sequence = torch.cat([sequence, padding])
else:
sequence = sequence[:self.seq_length]
return {
"input": sequence,
"label": sequence, # For autoencoder, etc.
"length": torch.tensor(min(len(self.sequences[i]), self.seq_length))
}
# Usage in training:
# from src.data_module.dataset import DatasetFactory
# dataset = DatasetFactory("time_series")(sequences=training_data, seq_length=128)
# dataloader = DataLoader(dataset, batch_size=32, shuffle=True)

View File

@@ -0,0 +1,217 @@
"""
Example: Creating a Custom Model
This example shows how to add a new model following the project architecture.
IMPORTANT: Models use a config-driven pattern where __init__ only accepts cfg.
Key Requirements:
- Use @register_model('ModelName') decorator
- __init__ accepts ONLY cfg parameter
- All hyperparameters come from cfg (cfg.model.*, cfg.dataset.*, etc.)
- forward() returns dict: {"loss": loss, "labels": labels, "logits": logits}
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Dict, Optional
# Import the register_model decorator
# Location may vary: src.model_module.brain_decoder or src.model_module.model
from src.model_module.brain_decoder import register_model
@register_model('SimpleMLP')
class SimpleMLP(nn.Module):
"""
Simple Multi-Layer Perceptron for classification tasks.
Config structure ( Hydra YAML ):
model:
input_dim: 100
hidden_dim: 256
output_dim: 10
num_layers: 3
dropout: 0.1
dataset:
task: classification # Used to get target_size
target_size:
classification: 10
"""
def __init__(self, cfg):
super().__init__()
# Store config
self.cfg = cfg
# Get task info from config
self.task = cfg.dataset.task
# Build model - ALL parameters from cfg
self.input_dim = cfg.model.input_dim
self.hidden_dim = cfg.model.get('hidden_dim', 256)
self.output_dim = cfg.dataset.target_size[cfg.dataset.task]
self.num_layers = cfg.model.get('num_layers', 3)
self.dropout = cfg.model.get('dropout', 0.1)
# Build layers
layers = []
in_dim = self.input_dim
for i in range(self.num_layers):
layers.extend([
nn.Linear(in_dim, self.hidden_dim),
nn.ReLU(),
nn.Dropout(self.dropout)
])
in_dim = self.hidden_dim
# Output layer
layers.append(nn.Linear(self.hidden_dim, self.output_dim))
self.network = nn.Sequential(*layers)
# Loss function
self.loss_fn = nn.CrossEntropyLoss()
def forward(
self,
x: torch.Tensor,
labels: Optional[torch.Tensor] = None,
**kwargs
) -> Dict[str, Optional[torch.Tensor]]:
"""
Forward pass.
Args:
x: Input tensor of shape (batch_size, input_dim)
labels: Ground truth labels (optional, for training)
Returns:
Dictionary with:
- loss: Computed loss (None if labels not provided)
- labels: Ground truth labels
- logits: Model predictions
"""
logits = self.network(x)
loss = None
if labels is not None:
# Convert labels to long type if needed
if labels.dtype != torch.long:
labels = labels.long()
loss = self.loss_fn(logits, labels)
return {
"loss": loss,
"labels": labels,
"logits": logits
}
# ============================================
# Example with Training/Inference Modes
# ============================================
@register_model('SimpleMLPWithModes')
class SimpleMLPWithModes(nn.Module):
"""
MLP with separate training and inference logic.
Shows how to handle different modes using self.training.
"""
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
self.task = cfg.dataset.task
self.input_dim = cfg.model.input_dim
self.hidden_dim = cfg.model.get('hidden_dim', 256)
self.output_dim = cfg.dataset.target_size[cfg.dataset.task]
self.fc_in = nn.Linear(self.input_dim, self.hidden_dim)
self.ln = nn.LayerNorm(self.hidden_dim)
self.fc_out = nn.Linear(self.hidden_dim, self.output_dim)
self.loss_fn = nn.CrossEntropyLoss()
# Test-time augmentation config
self.tta_times = cfg.model.get('tta_times', 1)
def forward(
self,
x: torch.Tensor,
labels: Optional[torch.Tensor] = None,
**kwargs
) -> Dict[str, Optional[torch.Tensor]]:
"""
Forward pass with training/inference modes.
"""
if self.training:
# Training mode
x = x.float()
x = self.fc_in(x)
x = self.ln(x)
x = F.relu(x)
logits = self.fc_out(x)
loss = None
if labels is not None:
if labels.dtype != torch.long:
labels = labels.long()
loss = self.loss_fn(logits, labels)
return {
"loss": loss,
"labels": labels,
"logits": logits
}
else:
# Inference mode with TTA
all_logits = []
with torch.no_grad():
x = x.float()
for _ in range(self.tta_times):
x_aug = x.clone()
# Apply TTA transformations here if needed
x_aug = self.fc_in(x_aug)
x_aug = self.ln(x_aug)
x_aug = F.relu(x_aug)
logits = self.fc_out(x_aug)
all_logits.append(logits)
# Average predictions
avg_logits = torch.mean(torch.stack(all_logits), dim=0)
loss = None
if labels is not None:
if labels.dtype != torch.long:
labels = labels.long()
loss = self.loss_fn(avg_logits, labels)
return {
"loss": loss,
"labels": labels,
"logits": avg_logits
}
# ============================================
# Config Example (Hydra YAML)
# ============================================
"""
# run/conf/model/simple_mlp.yaml
model:
name: SimpleMLP
input_dim: 100
hidden_dim: 256
output_dim: 10
num_layers: 3
dropout: 0.1
tta_times: 1
# Then in training pipeline:
# from src.model_module.brain_decoder import ModelFactory
# model = ModelFactory(cfg.model.name)(cfg)
"""

View File

@@ -0,0 +1,189 @@
#!/bin/bash
###############################################################################
# Training Pipeline Script
#
# This script demonstrates the standard training pipeline execution pattern.
# It handles environment setup, configuration, and execution with proper
# error handling and logging.
#
# Usage:
# ./run/pipeline/training/train.sh --config-name=config_example
###############################################################################
set -e # Exit on error
set -o pipefail # Exit on pipe failure
# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
EXPERIMENT_NAME="baseline_experiment"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
###############################################################################
# Helper Functions
###############################################################################
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
cleanup() {
log_info "Cleaning up..."
# Add cleanup logic here (e.g., kill background processes)
}
trap cleanup EXIT
###############################################################################
# Environment Setup
###############################################################################
setup_environment() {
log_info "Setting up environment..."
# Activate virtual environment if it exists
if [ -f "${PROJECT_ROOT}/.venv/bin/activate" ]; then
source "${PROJECT_ROOT}/.venv/bin/activate"
log_info "Activated virtual environment"
fi
# Check required commands
command -v python >/dev/null 2>&1 || { log_error "Python not found"; exit 1; }
# Set Python path
export PYTHONPATH="${PROJECT_ROOT}/src:${PYTHONPATH}"
log_info "PYTHONPATH set to: ${PYTHONPATH}"
}
###############################################################################
# Configuration
###############################################################################
parse_arguments() {
# Default values
CONFIG="default"
GPUS=0
SEED=42
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--config-name|-c)
CONFIG="$2"
shift 2
;;
--gpus|-g)
GPUS="$2"
shift 2
;;
--seed|-s)
SEED="$2"
shift 2
;;
*)
log_warn "Unknown argument: $1"
shift
;;
esac
done
log_info "Configuration: ${CONFIG}"
log_info "GPUs: ${GPUS}"
log_info "Seed: ${SEED}"
}
###############################################################################
# Main Training Function
###############################################################################
run_training() {
log_info "Starting training..."
# Output directory for this run
OUTPUT_DIR="${PROJECT_ROOT}/outputs/${EXPERIMENT_NAME}/${TIMESTAMP}"
mkdir -p "${OUTPUT_DIR}"
log_info "Output directory: ${OUTPUT_DIR}"
# Training command with Hydra
python "${PROJECT_ROOT}/train.py" \
--config-name="${CONFIG}" \
seed=${SEED} \
dir.output_dir="${OUTPUT_DIR}" \
training.device=cuda \
hydra.output_dir="${OUTPUT_DIR}/hydra" \
hydra.run.dir="${OUTPUT_DIR}/hydra" || {
log_error "Training failed!"
exit 1
}
log_info "Training completed successfully!"
}
###############################################################################
# Post-Processing
###############################################################################
post_process() {
log_info "Post-processing results..."
# Copy logs to output directory
if [ -f "${OUTPUT_DIR}/hydra/*.log" ]; then
cp "${OUTPUT_DIR}/hydra/"*.log "${OUTPUT_DIR}/"
fi
# Generate summary
log_info "Run summary:"
log_info " Config: ${CONFIG}"
log_info " Seed: ${SEED}"
log_info " Output: ${OUTPUT_DIR}"
# Print path to best checkpoint
BEST_CHECKPOINT=$(find "${OUTPUT_DIR}" -name "best*.pt" | head -n 1)
if [ -n "${BEST_CHECKPOINT}" ]; then
log_info " Best checkpoint: ${BEST_CHECKPOINT}"
fi
}
###############################################################################
# Main Execution
###############################################################################
main() {
log_info "=========================================="
log_info "Training Pipeline"
log_info "=========================================="
# Setup
setup_environment
# Parse arguments
parse_arguments "$@"
# Run training
run_training
# Post-process
post_process
log_info "=========================================="
log_info "Pipeline completed successfully!"
log_info "=========================================="
}
# Run main function
main "$@"

View File

@@ -0,0 +1,117 @@
# Auto-Import Pattern
## Overview
The Auto-Import pattern automatically discovers and imports all submodules in a directory, ensuring all components are registered without manual imports.
## Structure
```python
# In module __init__.py (e.g., data_module/dataset/__init__.py)
import os
from src.utils.helpers import import_modules
models_dir = os.path.dirname(__file__)
import_modules(models_dir, "src.data_module.dataset")
```
## Helper Function
```python
# In src/utils/helpers.py
import os
import importlib
import pkgutil
from typing import List
def import_modules(models_dir: str, package_name: str) -> List[str]:
"""
Import all Python modules in a directory.
Args:
models_dir: Directory path to scan
package_name: Full package name for imports
Returns:
List of imported module names
"""
imported = []
for module_loader, name, ispkg in pkgutil.iter_modules([models_dir]):
if not name.startswith('_'):
full_name = f"{package_name}.{name}"
importlib.import_module(full_name)
imported.append(name)
return imported
```
## Benefits
- **Zero maintenance**: Adding new file = auto-registration
- **No遗漏**: Cannot forget to import new component
- **Consistent**: All components follow same discovery path
- **Scalable**: Works for any number of submodules
## Implementation Details
1. Scan directory for `.py` files
2. Skip files starting with `_` (private)
3. Import each module using full package path
4. Import triggers decorator registration
## Directory Structure Example
```
dataset/
├── __init__.py # Contains import_modules() call
├── simple_dataset.py # Auto-imported, registers "simple"
├── custom_dataset.py # Auto-imported, registers "custom"
└── _private.py # NOT imported (starts with _)
```
## Best Practices
- **Skip private files**: Files starting with `_` are not imported
- **Full package paths**: Use dot-notation for correct imports
- **Idempotent**: Safe to call multiple times
- **Error handling**: Import errors propagate for debugging
## Common Patterns
### Conditional Import
```python
def import_modules(models_dir: str, package_name: str, skip: List[str] = None):
skip = skip or []
for module_loader, name, ispkg in pkgutil.iter_modules([models_dir]):
if name not in skip and not name.startswith('_'):
importlib.import_module(f"{package_name}.{name}")
```
### Recursive Import
```python
def import_modules_recursive(models_dir: str, package_name: str):
"""Import modules and subpackages recursively."""
for importer, name, ispkg in pkgutil.walk_packages([models_dir], prefix=f"{package_name}."):
if not name.split('.')[-1].startswith('_'):
importlib.import_module(name)
```
### Dry-Run Mode
```python
def import_modules(models_dir: str, package_name: str, dry_run: bool = False):
if dry_run:
return [name for _, name, _ in pkgutil.iter_modules([models_dir])
if not name.startswith('_')]
# ... actual import logic
```
## Integration with Registry
The auto-import pattern is typically used WITH registry pattern:
1. **Import time**: `import_modules()` imports all files
2. **Decorator execution**: `@register_dataset()` runs
3. **Factory population**: `DATASET_FACTORY` dict populated
4. **Runtime**: `DatasetFactory()` looks up registered classes

View File

@@ -0,0 +1,234 @@
# Code Style Guidelines
## Type Annotations
Always use type hints for function signatures and class attributes:
```python
from typing import Dict, List, Optional, Tuple
import torch
def __getitem__(self, i: int) -> Dict[str, torch.Tensor]:
"""Get item by index."""
return self.data[i]
def compute_metrics(predictions: torch.Tensor, labels: torch.Tensor) -> Dict[str, float]:
"""Compute evaluation metrics."""
pass
class MyModel(nn.Module):
hidden_dim: int # Class attribute type hints
output_dim: int
def __init__(self, cfg):
self.hidden_dim: int = cfg.model.hidden_dim
self.output_dim: int = cfg.model.output_dim
```
## Import Order
Organize imports in three sections with blank lines between:
```python
# 1. Standard library imports
import os
from typing import Dict, List, Optional
from pathlib import Path
# 2. Third-party imports
import torch
import torch.nn as nn
from torch.utils.data import Dataset
import numpy as np
# 3. Local imports
from src.data_module.dataset import register_dataset
from src.utils.helpers import import_modules
from src.model_module.brain_decoder import register_model
```
## __init__.py Files
### Module __init__.py (with factory)
Contains factory/registry logic and auto-import:
```python
# src/data_module/dataset/__init__.py
import os
from typing import Dict, Callable, TypeVar
from src.utils.helpers import import_modules
T = TypeVar('T')
DATASET_FACTORY: Dict[str, type] = {}
def register_dataset(name: str) -> Callable[[T], T]:
"""Decorator to register dataset classes."""
def decorator(cls: T) -> T:
DATASET_FACTORY[name] = cls
return cls
return decorator
def DatasetFactory(data_name: str):
"""Create dataset instance by name."""
dataset = DATASET_FACTORY.get(data_name, None)
if dataset is None:
dataset = DATASET_FACTORY.get('simple')
return dataset
# Auto-import all submodules
models_dir = os.path.dirname(__file__)
import_modules(models_dir, "src.data_module.dataset")
```
### Subpackage __init__.py (can be empty)
```python
# src/data_module/augmentation/__init__.py
# Empty file - just marks as package
```
Or with exports:
```python
# src/data_module/__init__.py
from .dataset import DatasetFactory, register_dataset
from .augmentation import AugmentationFactory
```
## Naming Conventions
### Files
- **Modules**: `simple_dataset.py`, `custom_model.py`
- **Pipelines**: `training.sh`, `inference.sh`
- **Configs**: `config.yaml`, `brain_decoder.yaml`
- **Utilities**: `get_optimizer.py`, `helpers.py`, `compute_metrics.py`
### Classes and Functions
```python
# Classes: PascalCase
class SimpleDataset(Dataset):
pass
class MyCustomModel(nn.Module):
pass
# Functions and variables: snake_case
def compute_accuracy(predictions, labels):
pass
def get_optimizer(cfg):
pass
learning_rate = 0.001
batch_size = 32
```
### Constants
```python
# Constants: UPPER_SNAKE_CASE
DEFAULT_HIDDEN_DIM = 256
MAX_EPOCHS = 100
LEARNING_RATE = 0.001
```
## Docstrings
Use Google-style docstrings:
```python
def DatasetFactory(data_name: str) -> type:
"""Create dataset class by name.
Args:
data_name: Name of the dataset to create.
Returns:
Dataset class if found, otherwise simple dataset.
Raises:
ValueError: If no dataset is found and no default exists.
"""
pass
```
## Configuration-Driven Classes
Model classes must be config-driven:
```python
@register_model('MyModel')
class MyModel(nn.Module):
def __init__(self, cfg):
"""Initialize model from config.
Args:
cfg: Hydra config object with model attributes.
"""
super().__init__()
self.cfg = cfg
# ALL parameters from cfg
self.hidden_dim = cfg.model.hidden_dim
self.output_dim = cfg.dataset.target_size[cfg.dataset.task]
self.dropout = cfg.model.dropout
def forward(self, x, labels=None, **kwargs):
"""Forward pass.
Args:
x: Input tensor.
labels: Ground truth labels (training mode).
**kwargs: Additional arguments.
Returns:
Dict with loss, labels, and logits.
"""
# Implementation
return {"loss": loss, "labels": labels, "logits": logits}
```
## Error Handling
```python
def DatasetFactory(data_name: str) -> type:
"""Create dataset class by name."""
dataset = DATASET_FACTORY.get(data_name)
if dataset is None:
available = ', '.join(DATASET_FACTORY.keys())
raise ValueError(
f"Dataset '{data_name}' not found. "
f"Available: {available}"
)
return dataset
```
## Logging
```python
import logging
logger = logging.getLogger(__name__)
@register_dataset('custom')
class CustomDataset(Dataset):
def __init__(self, cfg):
self.cfg = cfg
logger.info(f"Initializing {self.__class__.__name__}")
logger.debug(f"Config: {cfg.dataset}")
```
## Code Review Checklist
- [ ] All functions have type hints
- [ ] Imports are correctly ordered
- [ ] Classes use PascalCase, functions use snake_case
- [ ] Docstrings follow Google style
- [ ] Model classes are config-driven
- [ ] Registration decorators are used
- [ ] Error messages are informative
- [ ] Logging is added for key operations

View File

@@ -0,0 +1,53 @@
# Factory Pattern
## Overview
The Factory pattern allows dynamic creation of instances without specifying the exact class. Each module uses a factory to decouple creation from usage.
## Structure
```python
# In module __init__.py (e.g., data_module/dataset/__init__.py)
DATASET_FACTORY: Dict[str, type] = {}
def DatasetFactory(data_name: str):
"""Create dataset instance by name."""
dataset = DATASET_FACTORY.get(data_name, None)
if dataset is None:
# Fallback to default
dataset = DATASET_FACTORY.get('simple')
return dataset
```
## Usage
```python
# Consumer code doesn't need to know concrete class
dataset = DatasetFactory(cfg.dataset.name)
```
## Benefits
- **Loose coupling**: Consumer doesn't import concrete classes
- **Extensibility**: Add new types without changing consumer code
- **Fallback handling**: Graceful degradation for unknown types
- **Centralized registry**: Single source of truth for available types
## Implementation Details
1. Define factory dict at module level
2. Factory function handles lookup and fallback
3. Return class (not instance) for deferred initialization
4. None result triggers fallback to default implementation
## Common Patterns
```python
# With config integration
def DatasetFactory(cfg):
data_name = cfg.dataset.name
dataset_cls = DATASET_FACTORY.get(data_name)
if dataset_cls is None:
raise ValueError(f"Unknown dataset: {data_name}")
return dataset_cls(cfg)
```

View File

@@ -0,0 +1,102 @@
# Registry Pattern
## Overview
The Registry pattern allows components to register themselves via decorators, enabling automatic discovery and centralized management of available types.
## Structure
```python
# In module __init__.py (e.g., data_module/dataset/__init__.py)
from typing import Dict, Callable, TypeVar
T = TypeVar('T')
DATASET_FACTORY: Dict[str, type] = {}
def register_dataset(name: str) -> Callable[[T], T]:
"""Decorator to register dataset classes."""
def decorator(cls: T) -> T:
DATASET_FACTORY[name] = cls
return cls
return decorator
```
## Usage
```python
# In implementation file (e.g., simple_dataset.py)
from data_module.dataset import register_dataset
@register_dataset("simple")
class SimpleDataset(Dataset):
def __init__(self, cfg):
# Implementation
pass
```
## Benefits
- **Automatic registration**: Components register themselves on import
- **Declarative**: Single decorator line replaces manual registration code
- **Import-time discovery**: Auto-import pattern finds all implementations
- **Type-safe**: Preserves original class type
## Implementation Details
1. Decorator returns the class unchanged (for immediate use)
2. Side effect: adds class to factory dict
3. Name parameter must be unique per module
4. Registration happens at module import time
## Advanced Patterns
### Registration with Config
```python
def register_model(name: str):
def decorator(cls):
MODEL_FACTORY[name] = cls
# Add config validation
cls._config_schema = getattr(cls, '_config_schema', {})
return cls
return decorator
```
### Conditional Registration
```python
def register_dataset(name: str, experimental: bool = False):
def decorator(cls):
if not experimental or cfg.enable_experimental:
DATASET_FACTORY[name] = cls
return cls
return decorator
```
### Multi-Registry
```python
# Multiple registries in one module
DATASET_FACTORY = {}
AUGMENTATION_FACTORY = {}
def register_dataset(name: str):
def decorator(cls):
DATASET_FACTORY[name] = cls
return cls
return decorator
def register_augmentation(name: str):
def decorator(fn):
AUGMENTATION_FACTORY[name] = fn
return fn
return decorator
```
## Best Practices
- **Unique names**: Use descriptive, unique registration names
- **Documentation**: Document required parameters in class docstring
- **Validation**: Validate config in `__init__`, not in decorator
- **Consistency**: Use same naming convention across modules

View File

@@ -0,0 +1,150 @@
# Detailed Directory Structure
This document provides a comprehensive breakdown of the ML project template directory structure.
## Root Level Files
| File | Purpose |
|------|---------|
| `README.md` | Project documentation, installation guide, usage examples |
| `TODO.md` | Task tracking with weekly focus and daily tasks |
| `.gitignore` | Git ignore patterns for Python, Jupyter, IDEs, logs, cache |
| `pyproject.toml` | Project configuration for build system and dependencies |
| `uv.lock` | Locked dependency versions for reproducibility |
## run/ - Execution Layer
### pipeline/
Main workflow scripts organized by stage:
| Directory | Purpose |
|-----------|---------|
| `training/` | Training execution scripts (training.sh, inference.sh) |
| `prepare_data/` | Data preparation and preprocessing pipelines |
| `analysis/` | Evaluation and analysis workflows |
### conf/
Hydra configuration files organized by module:
| Directory | Purpose |
|-----------|---------|
| `training/` | Training hyperparameters, model configs, optimizer settings |
| `dataset/` | Dataset configurations, data paths, preprocessing options |
| `model/` | Model architecture configurations |
| `prepare_data/` | Data preparation parameters |
| `analysis/` | Analysis and evaluation configurations |
| `dir/` | Directory path configurations |
| `analysis/` | Analysis-specific settings |
## src/ - Source Code Layer
### data_module/ - Data Processing Module
```
data_module/
├── __init__.py # Module exports
├── utils.py # Data-specific utility functions
├── dataset/ # Dataset implementations
│ ├── __init__.py # Dataset factory and registry
│ └── simple_dataset.py # Simple dataset example
├── augmentation/ # Data augmentation methods
│ ├── __init__.py
│ ├── mixup.py # Mixup augmentation
│ ├── random_shift.py # Random shifting
│ ├── channel_mask.py # Channel masking
│ ├── time_masking.py # Time masking
│ └── add_noise.py # Noise injection
├── collate_fn/ # Batch collation functions
│ ├── __init__.py
│ └── simple_collate_fn.py
├── compute_metrics/ # Metrics computation
│ ├── __init__.py
│ └── simple_compute_metrics.py
├── prepare_data/ # Data preparation logic
│ ├── __init__.py
│ ├── prepare_data.py
│ └── generate_yaml.py
└── data_func/ # Data utility functions
├── __init__.py
└── simple_data_func.py
```
### model_module/ - Model Module
```
model_module/
├── __init__.py # Module exports
└── model/ # Model implementations
└── [model files]
```
### trainer_module/ - Training Module
Contains training loop logic, validation, and checkpoint management.
### analysis_module/ - Analysis Module
Contains evaluation, visualization, and result analysis code.
### llm/ - LLM Module
LLM-related code and integrations.
### utils/ - Shared Utilities
```
utils/
├── __init__.py
├── helpers.py # Helper functions (import_modules, etc.)
├── logging.py # Logging configuration
├── get_optimizer.py # Optimizer factory
├── get_scheduler.py # Learning rate scheduler factory
├── get_callback.py # Training callbacks
├── get_activation.py # Activation functions
└── get_checkpoint_aggregation.py # Checkpoint handling
```
## data/ - Data Layer
Following the Cookiecutter Data Science standard:
| Directory | Purpose |
|-----------|---------|
| `raw/` | Original, immutable data dump |
| `processed/` | Cleaned, transformed data ready for use |
| `external/` | Data from third-party sources |
## outputs/ - Output Layer
| Directory | Purpose |
|-----------|---------|
| `logs/` | Training logs, tensorboard logs |
| `checkpoints/` | Model checkpoints for resuming training |
| `tables/` | Result tables, CSV outputs |
| `figures/` | Plots, visualizations, figures |
## Module Interaction Flow
```
run/pipeline/ -> src/trainer_module/ -> src/model_module/
src/data_module/ src/utils/
src/utils/
run/conf/ -> Hydra config loader -> All modules
```
## File Naming Conventions
- **Modules**: `simple_dataset.py`, `custom_model.py`
- **Pipelines**: `training.sh`, `inference.sh`
- **Configs**: `config.yaml`, dataset-specific names
- **Utilities**: Descriptive names (`get_optimizer.py`, `helpers.py`)
## Python Package Structure
Each module is a proper Python package:
- Has `__init__.py` with factory/registry logic
- Can be imported as `from src.module import Component`
- Subpackages are automatically discovered via `import_modules()`

View File

@@ -0,0 +1,307 @@
---
name: bug-detective
description: This skill should be used when the user asks to "debug this", "fix this error", "investigate this bug", "troubleshoot this issue", "find the problem", "something is broken", "this isn't working", "why is this failing", or reports errors/exceptions/bugs. Provides systematic debugging workflow and common error patterns.
version: 0.1.0
---
# Bug Detective
A systematic debugging workflow for investigating and resolving code errors, exceptions, and failures. Provides structured debugging methods and common error pattern recognition.
## Core Philosophy
Debugging is a scientific problem-solving process that requires:
1. **Understand the problem** - Clearly define symptoms and expected behavior
2. **Gather evidence** - Collect error messages, logs, stack traces
3. **Form hypotheses** - Infer possible causes based on evidence
4. **Verify hypotheses** - Confirm or eliminate causes through experiments
5. **Resolve the issue** - Apply fixes and verify
## Debugging Workflow
### Step 1: Understand the Problem
Before starting to debug, clarify the following information:
**Required information to collect:**
- Complete error message content
- Exact location of the error (filename and line number)
- Reproduction steps (how to trigger the error)
- Expected behavior vs actual behavior
- Environment info (OS, versions, dependencies)
**Question template:**
```
1. What is the exact error message?
2. Which file and line does the error occur at?
3. How can this issue be reproduced? Provide detailed steps.
4. What was the expected result? What actually happened?
5. What recent changes might have introduced this issue?
```
### Step 2: Analyze Error Type
Choose a debugging strategy based on error type:
| Error Type | Characteristics | Debugging Method |
|-----------|----------------|-----------------|
| **Syntax Error** | Code cannot be parsed | Check syntax, bracket matching, quotes |
| **Import Error** | ModuleNotFoundError | Check module installation, path config |
| **Type Error** | TypeError | Check data types, type conversions |
| **Attribute Error** | AttributeError | Check if object attribute exists |
| **Key Error** | KeyError | Check if dictionary key exists |
| **Index Error** | IndexError | Check list/array index range |
| **Null Reference** | NoneType/NullPointerException | Check if variable is None |
| **Network Error** | ConnectionError/Timeout | Check network connection, URL, timeout settings |
| **Permission Error** | PermissionError | Check file permissions, user permissions |
| **Resource Error** | FileNotFoundError | Check if file path exists |
### Step 3: Locate the Problem Source
Use the following methods to locate the issue:
**1. Binary Search Method**
- Comment out half the code, check if the problem persists
- Progressively narrow the scope until the problematic code is found
**2. Log Tracing**
- Add print/logging statements at key locations
- Track variable value changes
- Confirm code execution path
**3. Breakpoint Debugging**
- Use debugger breakpoint functionality
- Step through code execution
- Inspect variable state
**4. Stack Trace Analysis**
- Find the call chain from the stack trace in the error message
- Determine the direct cause of the error
- Trace back to the root cause
### Step 4: Form and Verify Hypotheses
**Hypothesis framework:**
```
Hypothesis: [problem description] causes [error phenomenon]
Verification steps:
1. [verification method 1]
2. [verification method 2]
Expected results:
- If hypothesis is correct: [expected phenomenon]
- If hypothesis is wrong: [expected phenomenon]
```
### Step 5: Apply Fix
After fixing, verify:
1. The original error is resolved
2. No new errors have been introduced
3. Related functionality still works correctly
4. Tests added to prevent regression
## Python Common Error Patterns
### 1. Indentation Errors
### 2. Mutable Default Arguments
### 3. Closure Issues in Loops
### 4. Modifying a List While Iterating
### 5. Using `is` for String Comparison
### 6. Forgetting to Call `super().__init__()`
## JavaScript/TypeScript Common Error Patterns
### 1. `this` Binding Issues
### 2. Async Error Handling
### 3. Object Reference Comparison
## Bash/Zsh Common Error Patterns
### 1. Spacing Issues
```bash
# ❌ No spaces allowed in assignment
name = "John" # Error: tries to run 'name' command
# ✅ Correct assignment
name="John"
# ❌ Missing spaces in conditional test
if[$name -eq 1]; then # Error
# ✅ Correct
if [ $name -eq 1 ]; then
```
### 2. Quoting Issues
```bash
# ❌ Variables not expanded inside single quotes
echo 'The value is $var' # Output: The value is $var
# ✅ Use double quotes
echo "The value is $var" # Output: The value is actual_value
# ❌ Using backticks for command substitution (confusing)
result=`command`
# ✅ Use $()
result=$(command)
```
### 3. Unquoted Variables
```bash
# ❌ Unquoted variable, empty value causes errors
rm -rf $dir/* # If dir is empty, deletes all files in current directory
# ✅ Always quote variables
[ -n "$dir" ] && rm -rf "$dir"/*
# Or use set -u to prevent undefined variables
set -u # or set -o nounset
```
### 4. Variable Scope in Loops
```bash
# ❌ Pipe creates subshell, outer variable unchanged
cat file.txt | while read line; do
count=$((count + 1)) # Outer count won't change
done
echo "Total: $count" # Outputs 0
# ✅ Use process substitution or redirection
while read line; do
count=$((count + 1))
done < file.txt
echo "Total: $count" # Correct output
```
### 5. Array Operations
```bash
# ❌ Incorrect array access
arr=(1 2 3)
echo $arr[1] # Outputs 1[1]
# ✅ Correct array access
echo ${arr[1]} # Outputs 2
echo ${arr[@]} # Outputs all elements
echo ${#arr[@]} # Outputs array length
```
### 6. String Comparison
```bash
# ✅ Use `=` inside POSIX `[` tests and `==` inside Bash `[[ ]]` tests
if [ "$name" = "John" ]; then
if [[ "$name" == "John" ]]; then
# ❌ Using -eq for numeric comparison instead of =
if [ $age = 18 ]; then # Wrong
# ✅ Use arithmetic operators for numeric comparison
if [ $age -eq 18 ]; then
if (( age == 18 )); then
```
### 7. Command Failure Continues Execution
```bash
# ❌ Execution continues after command failure
cd /nonexistent
rm file.txt # Deletes file.txt in current directory
# ✅ Use set -e to exit on error
set -e # or set -o errexit
cd /nonexistent # Script exits here
rm file.txt
# Or check if command succeeded
cd /nonexistent || exit 1
```
## Common Debugging Commands
### Python pdb Debugger
```bash
python -m pdb script.py
pytest -x -vv tests/test_target.py
```
### Node.js Inspector
```bash
node --inspect-brk app.js
node --trace-warnings app.js
```
### Git Bisect
```bash
git bisect start
git bisect bad
git bisect good <known-good-commit>
```
### Bash Debugging
```bash
# Run script in debug mode
bash -x script.sh # Print each command
bash -v script.sh # Print command source
bash -n script.sh # Syntax check, no execution
# Enable debugging within a script
set -x # Enable command tracing
set -v # Enable verbose mode
set -e # Exit on error
set -u # Error on undefined variables
set -o pipefail # Fail if any command in pipe fails
```
## Preventive Debugging
### 1. Use Type Checking
### 2. Input Validation
### 3. Defensive Programming
### 4. Logging
## Debugging Checklist
### Before Starting
- [ ] Obtain the complete error message
- [ ] Record the stack trace of the error
- [ ] Confirm reproduction steps
- [ ] Understand expected behavior
### During Debugging
- [ ] Check recent code changes
- [ ] Use binary search to locate the issue
- [ ] Add logs to trace variables
- [ ] Verify hypotheses
### After Resolution
- [ ] Confirm the original error is fixed
- [ ] Test related functionality
- [ ] Add tests to prevent regression
- [ ] Document the problem and solution
## Additional Resources
### Reference Files
For detailed debugging techniques and patterns:
- **`references/python-errors.md`** - Python error details
- **`references/javascript-errors.md`** - JavaScript/TypeScript error details
- **`references/shell-errors.md`** - Bash/Zsh script error details
- **`references/debugging-tools.md`** - Debugging tools usage guide
- **`references/common-patterns.md`** - Common error patterns
### Example Files
Working debugging examples:
- **`examples/debugging-workflow.py`** - Complete debugging workflow example
- **`examples/error-handling-patterns.py`** - Error handling patterns
- **`examples/debugging-workflow.sh`** - Shell script debugging example

View File

@@ -0,0 +1,241 @@
"""
调试流程示例
这个示例展示了完整的调试流程,从发现问题到解决问题。
"""
import logging
# 配置日志
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ============================================
# 问题 1IndexError
# ============================================
def get_item(items, index):
"""
问题:直接访问索引可能导致 IndexError
错误现象:
IndexError: list index out of range
"""
# ❌ 有问题的代码
# return items[index]
# ✅ 修复后的代码
if 0 <= index < len(items):
return items[index]
else:
logger.warning(f"索引 {index} 超出范围 [0, {len(items)})")
return None
# ============================================
# 问题 2TypeError - 字符串拼接
# ============================================
def format_message(name, count):
"""
问题:尝试拼接字符串和数字
错误现象:
TypeError: can only concatenate str (not "int") to str
"""
# ❌ 有问题的代码
# return name + ": " + count
# ✅ 修复后的代码
return f"{name}: {count}"
# 或
# return name + ": " + str(count)
# ============================================
# 问题 3KeyError
# ============================================
def get_user_info(users, user_id):
"""
问题:直接访问字典中可能不存在的键
错误现象:
KeyError: 'user_123'
"""
# ❌ 有问题的代码
# return users[user_id]
# ✅ 修复后的代码 - 方法1使用 get()
return users.get(user_id, None)
# ✅ 修复后的代码 - 方法2检查键是否存在
# if user_id in users:
# return users[user_id]
# return None
# ============================================
# 问题 4AttributeError - None 对象
# ============================================
def process_data(data_provider):
"""
问题data_provider 可能返回 None
错误现象:
AttributeError: 'NoneType' object has no attribute 'process'
"""
data = data_provider.get_data()
# ❌ 有问题的代码
# return data.process()
# ✅ 修复后的代码
if data is not None:
return data.process()
else:
logger.error("数据为 None无法处理")
return None
# ============================================
# 问题 5修改正在迭代的列表
# ============================================
def remove_even_numbers(numbers):
"""
问题:迭代时修改列表导致跳过元素
错误现象:
某些偶数没有被移除
"""
# ❌ 有问题的代码
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num)
# return numbers
# ✅ 修复后的代码 - 方法1列表推导式
return [num for num in numbers if num % 2 != 0]
# ✅ 修复后的代码 - 方法2使用副本
# for num in numbers[:]:
# if num % 2 == 0:
# numbers.remove(num)
# return numbers
# ============================================
# 调试技巧示例
# ============================================
def debug_with_logging(data):
"""
使用日志追踪问题
"""
logger.debug(f"输入数据: {data}")
# 步骤 1
processed = step1(data)
logger.debug(f"步骤1结果: {processed}")
# 步骤 2
result = step2(processed)
logger.debug(f"步骤2结果: {result}")
return result
def step1(data):
"""模拟步骤1"""
return [x * 2 for x in data]
def step2(data):
"""模拟步骤2"""
return sum(data)
# ============================================
# 异常处理示例
# ============================================
def safe_divide(a, b):
"""
正确的异常处理模式
"""
try:
result = a / b
logger.info(f"{a} / {b} = {result}")
return result
except ZeroDivisionError:
logger.error(f"除数不能为零: {b}")
return None
except TypeError as e:
logger.error(f"类型错误: {e}")
return None
# ============================================
# 使用断言进行调试
# ============================================
def calculate_discount(price, discount_rate):
"""
使用断言验证假设
"""
# 断言:价格应该是正数
assert price > 0, f"价格应该是正数,实际: {price}"
# 断言:折扣率应该在 0-1 之间
assert 0 <= discount_rate <= 1, f"折扣率应该在 0-1 之间,实际: {discount_rate}"
discounted_price = price * (1 - discount_rate)
# 断言:折扣后的价格应该小于原价
assert discounted_price <= price, "折扣价格应该小于原价"
return discounted_price
# ============================================
# 测试代码
# ============================================
if __name__ == "__main__":
print("=" * 50)
print("调试示例")
print("=" * 50)
# 测试 get_item
print("\n1. 测试 get_item:")
items = ['a', 'b', 'c']
print(f"get_item(items, 1) = {get_item(items, 1)}")
print(f"get_item(items, 10) = {get_item(items, 10)}")
# 测试 format_message
print("\n2. 测试 format_message:")
print(f"format_message('Count', 42) = {format_message('Count', 42)}")
# 测试 get_user_info
print("\n3. 测试 get_user_info:")
users = {'user_1': 'Alice', 'user_2': 'Bob'}
print(f"get_user_info(users, 'user_1') = {get_user_info(users, 'user_1')}")
print(f"get_user_info(users, 'user_999') = {get_user_info(users, 'user_999')}")
# 测试 remove_even_numbers
print("\n4. 测试 remove_even_numbers:")
numbers = [1, 2, 3, 4, 5, 6]
print(f"原始: {numbers}")
print(f"结果: {remove_even_numbers(numbers)}")
# 测试 safe_divide
print("\n5. 测试 safe_divide:")
print(f"safe_divide(10, 2) = {safe_divide(10, 2)}")
print(f"safe_divide(10, 0) = {safe_divide(10, 0)}")
# 测试 calculate_discount
print("\n6. 测试 calculate_discount:")
print(f"calculate_discount(100, 0.2) = {calculate_discount(100, 0.2)}")

View File

@@ -0,0 +1,400 @@
#!/bin/bash
#
# Shell 脚本调试流程示例
# 展示常见的 Bash 脚本错误和调试方法
#
# ============================================
# 调试设置
# ============================================
# 取消注释以启用调试模式
# set -x # 打印每个命令
# set -e # 错误时退出
# set -u # 未定义变量报错
# set -o pipefail # 管道中任何命令失败则失败
# 或组合使用
# set -xeuo pipefail # 严格模式
# ============================================
# 错误处理函数
# ============================================
# 错误退出函数
die() {
local message="$1"
local exit_code="${2:-1}"
echo "Error: $message" >&2
exit "$exit_code"
}
# 记录函数
log() {
local level="$1"
shift
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" >&2
}
log_info() { log "INFO" "$@"; }
log_warn() { log "WARN" "$@"; }
log_error() { log "ERROR" "$@"; }
# ============================================
# 问题 1未引用的变量
# ============================================
# 错误示例:变量未引用
demo_unquoted_variable() {
echo "=== 问题 1未引用的变量 ==="
local name="John Doe"
# 错误:变量未引用,空值会导致语法错误
# if [ $name = "John Doe" ]; then
# echo "Match"
# fi
# 正确:始终引用变量
if [ "$name" = "John Doe" ]; then
log_info "变量匹配: $name"
fi
}
# ============================================
# 问题 2命令失败继续执行
# ============================================
demo_command_failure() {
echo "=== 问题 2命令失败继续执行 ==="
# 错误cd 失败后继续执行
# cd /nonexistent_directory
# rm -rf file.txt # 会删除当前目录的文件!
# 正确:检查命令是否成功
cd /tmp || die "无法切换到 /tmp 目录"
log_info "成功切换到目录: $(pwd)"
cd - > /dev/null || true
}
# ============================================
# 问题 3循环中的变量作用域管道问题
# ============================================
demo_pipeline_scope() {
echo "=== 问题 3管道中的变量作用域 ==="
local count=0
# 错误:管道创建子 shell外部变量不改变
# echo -e "1\n2\n3" | while read line; do
# count=$((count + 1))
# done
# echo "Count: $count" # 输出 0
# 正确:使用重定向
while read line; do
count=$((count + 1))
done < <(echo -e "1\n2\n3")
log_info "计数结果: $count"
}
# ============================================
# 问题 4数组操作
# ============================================
demo_array_operations() {
echo "=== 问题 4数组操作 ==="
local fruits=("apple" "banana" "cherry")
# 错误的数组访问
# echo $fruits[1] # 输出 apple[1]
# 正确的数组访问
log_info "第一个元素: ${fruits[0]}"
log_info "第二个元素: ${fruits[1]}"
log_info "所有元素: ${fruits[@]}"
log_info "数组长度: ${#fruits[@]}"
# 遍历数组
for fruit in "${fruits[@]}"; do
log_info "水果: $fruit"
done
}
# ============================================
# 问题 5字符串比较
# ============================================
demo_string_comparison() {
echo "=== 问题 5字符串比较 ==="
local name="John"
# 错误:数字比较使用 =
# if [ $age = 18 ]; then
# 正确:字符串比较
if [[ "$name" == "John" ]]; then
log_info "字符串匹配"
fi
# 正确:数字比较
local age=18
if [ "$age" -eq 18 ]; then
log_info "数字匹配"
fi
}
# ============================================
# 问题 6算术运算
# ============================================
demo_arithmetic() {
echo "=== 问题 6算术运算 ==="
local a=10
local b=5
# 错误:使用 let 或 $(())
# result = a + b # 这是命令调用
# 正确的算术运算
local result=$((a + b))
log_info "加法: $a + $b = $result"
result=$((a - b))
log_info "减法: $a - $b = $result"
result=$((a * b))
log_info "乘法: $a * $b = $result"
result=$((a / b))
log_info "除法: $a / $b = $result"
# 使用 let
let result=a+b
log_info "let 加法: $result"
}
# ============================================
# 参数验证
# ============================================
validate_arguments() {
echo "=== 参数验证 ==="
# 检查参数数量
if [ $# -lt 2 ]; then
die "用法: $0 <文件> <目录>" 2
fi
local file="$1"
local dir="$2"
# 检查文件存在
if [ ! -f "$file" ]; then
die "文件不存在: $file" 3
fi
# 检查目录存在
if [ ! -d "$dir" ]; then
die "目录不存在: $dir" 4
fi
log_info "参数验证通过"
log_info "文件: $file"
log_info "目录: $dir"
}
# ============================================
# 使用 trap 进行清理
# ============================================
demo_trap() {
echo "=== 使用 trap 进行清理 ==="
# 设置清理函数
cleanup() {
log_info "执行清理操作..."
# 这里可以执行清理操作
}
# 捕获退出信号
trap cleanup EXIT
# 捕获错误信号
trap 'log_error "发生错误,行号: $LINENO"' ERR
# 捕获中断信号
trap 'log_warn "脚本被中断"; cleanup; exit 130' INT
log_info "执行一些操作..."
# 模拟操作
sleep 1
}
# ============================================
# 调试技巧示例
# ============================================
demo_debugging() {
echo "=== 调试技巧 ==="
# 1. 使用 echo 调试
local value="test"
echo "[DEBUG] value = $value" >&2
# 2. 使用 printf 格式化输出
printf "[DEBUG] Count: %d, Name: %s\n" 42 "John" >&2
# 3. 检查变量是否设置
if [ -z "${unset_var+x}" ]; then
log_warn "变量 unset_var 未设置"
fi
# 4. 显示调用栈
log_info "调用栈:"
local i=0
while caller $i; do
((i++))
done 2>/dev/null || true
}
# ============================================
# 文件操作错误处理
# ============================================
demo_file_operations() {
echo "=== 文件操作错误处理 ==="
local tmpfile=$(mktemp) || die "无法创建临时文件"
# 确保文件被删除
trap "rm -f '$tmpfile'" EXIT
# 写入文件
echo "Test content" > "$tmpfile" || die "无法写入文件: $tmpfile"
# 读取文件
local content
content=$(cat "$tmpfile") || die "无法读取文件: $tmpfile"
log_info "文件内容: $content"
# trap 会自动清理
}
# ============================================
# 带重试的操作
# ============================================
demo_retry() {
echo "=== 带重试的操作 ==="
local max_attempts=3
local attempt=1
while [ $attempt -le $max_attempts ]; do
log_info "尝试 $attempt/$max_attempts..."
# 模拟可能失败的操作
if [ $attempt -eq 2 ]; then
log_info "成功!"
return 0
fi
log_warn "失败,重试..."
((attempt++))
sleep 1
done
log_error "所有尝试都失败了"
return 1
}
# ============================================
# 检查依赖
# ============================================
check_dependencies() {
echo "=== 检查依赖 ==="
local required_commands=("curl" "jq" "git")
for cmd in "${required_commands[@]}"; do
if ! command -v "$cmd" &> /dev/null; then
log_error "缺少依赖: $cmd"
return 1
fi
log_info "$cmd 可用"
done
log_info "所有依赖都已满足"
}
# ============================================
# 主函数
# ============================================
main() {
echo "============================================"
echo "Shell 脚本调试示例"
echo "============================================"
# 运行各个示例
demo_unquoted_variable
echo ""
demo_command_failure
echo ""
demo_pipeline_scope
echo ""
demo_array_operations
echo ""
demo_string_comparison
echo ""
demo_arithmetic
echo ""
demo_trap
echo ""
demo_debugging
echo ""
demo_file_operations
echo ""
demo_retry
echo ""
check_dependencies
echo ""
log_info "所有示例执行完成"
}
# 运行主函数
main "$@"

View File

@@ -0,0 +1,305 @@
"""
错误处理模式示例
展示各种错误处理的最佳实践
"""
import logging
from typing import Optional, List, Dict, Any
from functools import wraps
logger = logging.getLogger(__name__)
# ============================================
# 模式 1具体异常捕获
# ============================================
def read_file(filepath: str) -> Optional[str]:
"""
捕获具体异常而不是宽泛的 Exception
"""
try:
with open(filepath, 'r') as f:
return f.read()
except FileNotFoundError:
logger.error(f"文件不存在: {filepath}")
return None
except PermissionError:
logger.error(f"没有权限读取文件: {filepath}")
return None
except UnicodeDecodeError:
logger.error(f"文件编码错误: {filepath}")
return None
# ============================================
# 模式 2带重试的操作
# ============================================
def retry_operation(max_attempts: int = 3):
"""
装饰器:自动重试失败的操作
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts:
logger.error(f"操作失败,已重试 {max_attempts} 次: {e}")
raise
logger.warning(f"操作失败,第 {attempt} 次重试...")
return None
return wrapper
return decorator
@retry_operation(max_attempts=3)
def unstable_api_call() -> Dict[str, Any]:
"""
模拟不稳定的 API 调用
"""
import random
if random.random() < 0.7: # 70% 失败率
raise ConnectionError("API 连接失败")
return {"status": "success", "data": "result"}
# ============================================
# 模式 3上下文管理器处理资源
# ============================================
class DatabaseConnection:
"""
自定义上下文管理器,确保资源正确释放
"""
def __init__(self, connection_string: str):
self.connection_string = connection_string
self.connection = None
def __enter__(self):
logger.info(f"连接数据库: {self.connection_string}")
self.connection = f"Connection to {self.connection_string}"
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
logger.error(f"发生异常: {exc_val}")
logger.info("关闭数据库连接")
# 清理资源
self.connection = None
return False # 不抑制异常
# ============================================
# 模式 4链式异常保留原始异常
# ============================================
def validate_and_process(data: Dict[str, Any]) -> Any:
"""
使用 raise from 保留原始异常链
"""
try:
# 验证数据
if 'value' not in data:
raise ValueError("数据中缺少 'value' 字段")
value = data['value']
if not isinstance(value, (int, float)):
raise TypeError(f"value 应该是数字,实际类型: {type(value)}")
# 处理数据
return value * 2
except (ValueError, TypeError) as e:
# 保留原始异常并添加上下文
raise RuntimeError(f"数据处理失败: {data}") from e
# ============================================
# 模式 5结果对象模式不使用异常
# ============================================
class Result:
"""
结果对象模式:封装成功/失败状态
"""
def __init__(self, success: bool, value: Any = None, error: str = None):
self.success = success
self.value = value
self.error = error
@classmethod
def ok(cls, value: Any) -> 'Result':
return cls(success=True, value=value)
@classmethod
def err(cls, error: str) -> 'Result':
return cls(success=False, error=error)
def is_ok(self) -> bool:
return self.success
def is_err(self) -> bool:
return not self.success
def unwrap(self) -> Any:
if not self.success:
raise ValueError(f"尝试解包错误结果: {self.error}")
return self.value
def unwrap_or(self, default: Any) -> Any:
return self.value if self.success else default
def safe_divide_result(a: float, b: float) -> Result:
"""
使用结果对象而不是异常
"""
if b == 0:
return Result.err(f"除数不能为零: {b}")
try:
return Result.ok(a / b)
except Exception as e:
return Result.err(f"计算失败: {e}")
# ============================================
# 模式 6多项验证错误收集
# ============================================
class ValidationError(Exception):
"""自定义验证错误"""
def __init__(self, errors: List[str]):
self.errors = errors
super().__init__("\n".join(errors))
def validate_user(data: Dict[str, Any]) -> None:
"""
收集所有验证错误而不是遇到第一个就停止
"""
errors = []
if 'name' not in data:
errors.append("缺少 'name' 字段")
elif not isinstance(data['name'], str):
errors.append("'name' 应该是字符串")
elif len(data['name']) < 2:
errors.append("'name' 长度应该至少为 2")
if 'age' not in data:
errors.append("缺少 'age' 字段")
elif not isinstance(data['age'], int):
errors.append("'age' 应该是整数")
elif data['age'] < 0 or data['age'] > 150:
errors.append("'age' 应该在 0-150 之间")
if 'email' in data and '@' not in data['email']:
errors.append("'email' 格式不正确")
if errors:
raise ValidationError(errors)
# ============================================
# 模式 7默认值和回退
# ============================================
def get_config(config: Dict[str, Any], key: str, default: Any = None) -> Any:
"""
安全获取配置,支持多级键和默认值
"""
if '.' in key:
# 支持嵌套键,如 "database.host"
keys = key.split('.')
value = config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return default
return value
# 简单键
return config.get(key, default)
# ============================================
# 模式 8优雅降级
# ============================================
def get_user_preferences(user_id: int) -> Dict[str, Any]:
"""
尝试多种方法获取用户偏好,优雅降级
"""
# 尝试 1从缓存获取
try:
return _get_from_cache(user_id)
except Exception as e:
logger.warning(f"从缓存获取失败: {e}")
# 尝试 2从数据库获取
try:
return _get_from_database(user_id)
except Exception as e:
logger.warning(f"从数据库获取失败: {e}")
# 尝试 3使用默认配置
logger.info("使用默认配置")
return _get_default_preferences()
def _get_from_cache(user_id: int) -> Dict[str, Any]:
# 模拟缓存失败
raise ConnectionError("缓存连接失败")
def _get_from_database(user_id: int) -> Dict[str, Any]:
# 模拟数据库失败
raise ConnectionError("数据库连接失败")
def _get_default_preferences() -> Dict[str, Any]:
return {
"theme": "light",
"language": "zh-CN",
"notifications": True
}
# ============================================
# 测试代码
# ============================================
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
print("=" * 50)
print("错误处理模式示例")
print("=" * 50)
# 测试结果对象模式
print("\n1. 结果对象模式:")
result1 = safe_divide_result(10, 2)
print(f"10 / 2 = {result1.unwrap()}")
result2 = safe_divide_result(10, 0)
print(f"10 / 0 = {result2.unwrap_or('N/A')} ({result2.error})")
# 测试优雅降级
print("\n2. 优雅降级:")
prefs = get_user_preferences(123)
print(f"用户偏好: {prefs}")
# 测试上下文管理器
print("\n3. 上下文管理器:")
try:
with DatabaseConnection("localhost:5432") as conn:
print(f"连接: {conn}")
except Exception as e:
print(f"操作失败: {e}")

View File

@@ -0,0 +1,308 @@
# 常见错误模式
## 通用编程错误模式
### 1. Off-by-one Error差一错误
**描述**:循环或索引中出现 ±1 的偏差
**示例**
```python
# ❌ 错误:范围应该是 range(n) 而不是 range(n+1)
for i in range(len(items) + 1):
print(items[i]) # IndexError
# ✅ 正确
for i in range(len(items)):
print(items[i])
```
### 2. Null/None 引用错误
**描述**:尝试访问 None 对象的属性或方法
**Python**
```python
# ❌ 可能返回 None
result = get_data()
print(result.value) # AttributeError
# ✅ 检查 None
result = get_data()
if result is not None:
print(result.value)
```
**JavaScript**
```javascript
// ❌ 可能是 null
const user = getUser();
console.log(user.name); // TypeError
// ✅ 使用可选链
console.log(user?.name);
```
### 3. 资源泄漏
**描述**:打开的资源(文件、连接)未正确关闭
**Python**
```python
# ❌ 文件可能未关闭
f = open("file.txt")
content = f.read()
# 如果发生异常,文件不会关闭
# ✅ 使用 with 语句
with open("file.txt") as f:
content = f.read()
# 文件自动关闭
```
### 4. 竞态条件
**描述**:多线程/进程间的时序依赖问题
**示例**
```python
# ❌ 检查后使用TOCTOU
if os.path.exists("file.txt"):
# 其他进程可能在这之间删除文件
with open("file.txt") as f:
content = f.read()
# ✅ 直接尝试并处理异常
try:
with open("file.txt") as f:
content = f.read()
except FileNotFoundError:
content = None
```
### 5. 忘记返回值
**描述**:函数没有显式返回值,导致返回 None
**示例**
```python
# ❌ 忘记返回结果
def calculate(x, y):
result = x + y
# 忘记 return
# ✅ 正确返回
def calculate(x, y):
return x + y
```
### 6. 错误的比较运算符
**描述**:使用 = 代替 ==,或混淆 is 和 ==
**Python**
```python
# ❌ 赋值而不是比较
if x = 5: # SyntaxError
# ❌ 使用 is 比较值
if x is 5: # 不保证正确
# ✅ 正确
if x == 5:
```
### 7. 浮点数精度问题
**描述**:浮点数比较因精度问题失败
**示例**
```python
# ❌ 直接比较浮点数
if 0.1 + 0.2 == 0.3: # False
print("相等")
# ✅ 使用容差比较
if abs((0.1 + 0.2) - 0.3) < 1e-9:
print("相等")
# 或使用 math.isclose()
import math
if math.isclose(0.1 + 0.2, 0.3):
print("相等")
```
### 8. 字符串拼接性能问题
**描述**:在循环中使用 + 拼接字符串
**示例**
```python
# ❌ 低效:每次创建新字符串
result = ""
for item in items:
result += str(item)
# ✅ 高效:使用列表和 join
result = "".join(str(item) for item in items)
```
## Python 特有模式
### 1. 可变默认参数
```python
# ❌ 所有调用共享同一个列表
def append(item, items=[]):
items.append(item)
return items
# ✅ 使用 None 作为默认值
def append(item, items=None):
if items is None:
items = []
items.append(item)
return items
```
### 2. 闭包变量绑定问题
```python
# ❌ 所有函数使用相同的 i 值
funcs = [lambda: i for i in range(3)]
# 所有函数都返回 2
# ✅ 使用默认参数捕获值
funcs = [lambda i=i: i for i in range(3)]
```
### 3. 修改正在迭代的序列
```python
# ❌ 迭代时修改列表
items = [1, 2, 3, 4]
for item in items:
if item % 2 == 0:
items.remove(item)
# ✅ 创建新列表或使用副本
items = [item for item in items if item % 2 != 0]
# 或
for item in items[:]:
if item % 2 == 0:
items.remove(item)
```
## JavaScript/TypeScript 特有模式
### 1. this 绑定问题
```javascript
// ❌ this 丢失上下文
class Counter {
count = 0;
increment() {
setTimeout(function() {
this.count++; // this 不是 Counter 实例
}, 100);
}
}
// ✅ 使用箭头函数
class Counter {
count = 0;
increment() {
setTimeout(() => {
this.count++; // this 正确绑定
}, 100);
}
}
```
### 2. 异步错误处理
```javascript
// ❌ 没有处理 Promise 错误
async function getData() {
const response = await fetch(url);
return response.json(); // 如果失败会抛出异常
}
// ✅ 使用 try-catch
async function getData() {
try {
const response = await fetch(url);
return await response.json();
} catch (error) {
console.error("获取数据失败:", error);
throw error;
}
}
```
### 3. 数组/对象引用
```javascript
// ❌ 直接赋值会复制引用
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr2.push(4); // arr1 也会被修改
// ✅ 创建副本
const arr2 = [...arr1]; // 或 arr1.slice()
// 对象
const obj1 = { a: 1 };
const obj2 = { ...obj1 }; // 或 Object.assign({}, obj1)
```
## 并发错误模式
### 1. 死锁
```python
# ❌ 可能死锁
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def thread1():
with lock1:
with lock2:
# 操作
def thread2():
with lock2:
with lock1: # 死锁
# 操作
```
### 2. 数据竞争
```python
# ❌ 多个线程同时修改共享变量
counter = 0
def increment():
global counter
counter += 1 # 非原子操作
# ✅ 使用锁
counter = 0
lock = threading.Lock()
def increment():
global counter
with lock:
counter += 1
```
## 预防措施
1. **使用类型检查**TypeScript、Python 类型注解
2. **编写单元测试**:覆盖边界条件
3. **使用静态分析工具**pylint、eslint
4. **代码审查**:让他人检查代码
5. **使用防御性编程**:验证输入、处理异常

View File

@@ -0,0 +1,29 @@
# Debugging Tools
## Python
```bash
python -m pdb script.py
python -m traceback your_script.py
pytest -x -vv tests/test_target.py
```
## Node.js
```bash
node --inspect-brk app.js
node --trace-warnings app.js
npm test -- --runInBand
```
## Git
```bash
git bisect start
git bisect bad
git bisect good <known-good-commit>
```
## Shell
```bash
bash -n script.sh
bash -x script.sh
shellcheck script.sh
```

View File

@@ -0,0 +1,14 @@
# JavaScript / TypeScript Error Guide
## Frequent failure classes
- `TypeError` from undefined/null access
- async error swallowing in `Promise` chains
- `this` binding mismatches
- stale closure bugs in hooks or event handlers
- ESM / CJS import mismatches
## Minimum debugging flow
1. copy the full stack trace,
2. identify whether the failure is runtime, bundler, or type-level,
3. confirm the failing object/value before changing logic,
4. reproduce with the smallest possible input.

View File

@@ -0,0 +1,311 @@
# Python 错误详解
## 常见内置异常类型
### 1. SyntaxError语法错误
**特征**:代码无法解析,在运行前就被检测到
**常见原因**
- 括号不匹配
- 缺少冒号
- 缩进不正确
- 引号不匹配
**示例**
```python
# ❌ 缺少冒号
if True
print("missing colon")
# ✅ 正确
if True:
print("has colon")
```
### 2. IndentationError缩进错误
**特征**:缩进不一致或使用错误的缩进
**常见原因**
- 混用 Tab 和空格
- 缩进级别不正确
**示例**
```python
# ❌ 混用空格和 Tab
def test():
print("mixed") # Tab
print("spaces") # 空格
# ✅ 统一使用 4 个空格
def test():
print("spaces")
print("consistent")
```
### 3. NameError名称错误
**特征**:变量或函数名不存在
**常见原因**
- 变量未定义就使用
- 函数名拼写错误
- 变量作用域问题
**示例**
```python
# ❌ 变量未定义
print(undefined_var)
# ✅ 先定义再使用
my_var = 42
print(my_var)
```
### 4. TypeError类型错误
**特征**:操作或函数应用于错误的数据类型
**常见原因**
- 拼接不同类型
- 函数参数类型错误
- 对不支持的操作使用运算符
**示例**
```python
# ❌ 拼接字符串和数字
result = "Value: " + 42
# ✅ 转换类型
result = "Value: " + str(42)
# 或使用 f-string
result = f"Value: {42}"
```
### 5. AttributeError属性错误
**特征**:对象没有指定的属性或方法
**常见原因**
- 属性名拼写错误
- 对象类型不是预期的
- 大小写错误
**示例**
```python
# ❌ 列表没有 append 以外的方法
my_list = [1, 2, 3]
my_list.push(4) # 列表没有 push 方法
# ✅ 使用正确的方法
my_list.append(4)
```
### 6. KeyError键错误
**特征**:字典中不存在指定的键
**常见原因**
- 键名拼写错误
- 键不存在于字典中
**示例**
```python
data = {"name": "Alice"}
# ❌ 直接访问不存在的键
age = data["age"] # KeyError
# ✅ 使用 get() 方法
age = data.get("age", 0) # 返回默认值 0
```
### 7. IndexError索引错误
**特征**:序列索引超出范围
**常见原因**
- 索引为负数(除非是有意为之)
- 索引大于序列长度-1
- 序列为空时访问索引
**示例**
```python
items = [1, 2, 3]
# ❌ 索引超出范围
item = items[5] # IndexError
# ✅ 检查长度后再访问
if len(items) > 5:
item = items[5]
else:
item = None
```
### 8. ValueError值错误
**特征**:参数类型正确但值不合适
**常见原因**
- 字符串转整数失败
- 数学运算值域错误
- 参数值不在允许范围内
**示例**
```python
# ❌ 无法转换为整数
num = int("abc")
# ✅ 处理可能的错误
try:
num = int(input())
except ValueError:
num = 0
```
### 9. ImportError / ModuleNotFoundError导入错误
**特征**:无法导入模块
**常见原因**
- 模块未安装
- 模块路径不在 PYTHONPATH 中
- 模块名拼写错误
**示例**
```python
# ❌ 模块未安装
import missing_module
# 解决方法:安装模块
# pip install missing-module
```
### 10. FileNotFoundError文件未找到错误
**特征**:尝试打开不存在的文件
**常见原因**
- 文件路径错误
- 文件不存在
- 相对路径使用错误
**示例**
```python
# ❌ 文件不存在
with open("missing.txt") as f:
content = f.read()
# ✅ 使用 try-except 或检查文件存在
try:
with open("file.txt") as f:
content = f.read()
except FileNotFoundError:
content = ""
```
## 异常处理最佳实践
### 1. 捕获具体异常
```python
# ❌ 捕获所有异常(不良实践)
try:
result = dangerous_operation()
except:
pass
# ✅ 捕获具体异常
try:
result = dangerous_operation()
except (ValueError, TypeError) as e:
logger.error(f"操作失败: {e}")
```
### 2. 使用 finally 清理资源
```python
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
content = ""
finally:
# 无论是否发生异常都会执行
if 'file' in locals():
file.close()
```
### 3. 使用上下文管理器
```python
# ✅ 推荐:使用 with 语句
with open("data.txt", "r") as file:
content = file.read()
# 文件会自动关闭
```
### 4. 链式异常
```python
try:
process_data(data)
except ValueError as e:
# 使用 raise from 保留原始异常
raise RuntimeError("数据处理失败") from e
```
## 调试技巧
### 1. 使用 traceback 模块
```python
import traceback
try:
risky_operation()
except Exception:
# 打印完整的堆栈跟踪
traceback.print_exc()
```
### 2. 使用 pdb 调试器
```python
import pdb
# 在代码中设置断点
pdb.set_trace()
# 或使用 breakpoint() (Python 3.7+)
breakpoint()
```
### 3. 使用 logging 模块
```python
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug("调试信息")
logger.info("普通信息")
logger.warning("警告")
logger.error("错误")
logger.critical("严重错误")
```
## 常见错误排查清单
- [ ] 检查拼写(变量名、函数名、属性名)
- [ ] 检查数据类型(使用 type() 函数)
- [ ] 检查变量值(使用 print() 或调试器)
- [ ] 检查索引和键是否在范围内
- [ ] 检查文件路径是否正确
- [ ] 检查缩进是否一致
- [ ] 检查括号、引号是否匹配
- [ ] 检查是否正确导入了模块
- [ ] 检查异常是否被正确处理

View File

@@ -0,0 +1,236 @@
# Bash/Zsh 脚本错误详解
## 常见错误类型
### 1. Command Not Found
**特征**bash: command: command not found
**常见原因**
- 命令拼写错误
- 命令未安装
- PATH 环境变量不正确
- 脚本 shebang 错误
**示例**
```bash
# 拼写错误
pyhon script.py # command not found
# 正确拼写
python script.py
# PATH 问题
/usr/local/bin/mycommand # 如果 PATH 不包含 /usr/local/bin
# 使用完整路径或添加到 PATH
export PATH="/usr/local/bin:$PATH"
mycommand
```
### 2. Syntax Error
**特征**syntax error near unexpected token
**常见原因**
- 缺少 then/fi/done/ esac
- 括号不匹配
- 操作符缺少空格
**示例**
```bash
# 缺少 then
if [ 1 -eq 1 ]
echo "yes" # syntax error
# 正确
if [ 1 -eq 1 ]; then
echo "yes"
fi
```
### 3. Permission Denied
**特征**bash: ./script.sh: Permission denied
**解决方案**
```bash
# 添加执行权限
chmod +x script.sh
# 或使用 bash 运行
bash script.sh
```
## 调试技巧
### 1. 使用 set -x 追踪执行
```bash
#!/bin/bash
set -x # 启用命令追踪
name="John"
echo "Hello $name"
# 输出:
# + name=John
# + echo 'Hello John'
# Hello John
```
### 2. 使用 set -e 遇错退出
```bash
#!/bin/bash
set -e # 任何命令失败时退出
cd /nonexistent # 脚本在此处退出
echo "This won't run"
```
### 3. 使用 set -u 检测未定义变量
```bash
#!/bin/bash
set -u # 未定义变量时报错
echo $undefined_var # 报错并退出
```
### 4. 组合使用调试选项
```bash
#!/bin/bash
set -xeuo pipefail # 严格模式
# -x: 打印每个命令
# -e: 错误时退出
# -u: 未定义变量报错
# -o pipefail: 管道失败则失败
```
### 5. 使用 trap 捕获错误
```bash
#!/bin/bash
# 在脚本退出时执行清理
trap 'echo "Script exited with code $?"' EXIT
# 在错误时执行
trap 'echo "Error on line $LINENO"' ERR
# 在中断时执行
trap 'echo "Interrupted"; cleanup' INT
```
## 错误处理模式
### 1. 检查命令退出码
```bash
# 检查上一个命令是否成功
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failed"
fi
# 或使用 ||
command || { echo "Failed"; exit 1; }
# 或使用 &&
command && echo "Success" || echo "Failed"
```
### 2. 使用函数封装错误处理
```bash
# 定义错误处理函数
die() {
local message=$1
echo "Error: $message" >&2
exit 1
}
# 使用
[ -f "$file" ] || die "File not found: $file"
```
### 3. 验证输入参数
```bash
#!/bin/bash
# 检查参数数量
[ $# -ge 1 ] || die "Usage: $0 <arg1> [arg2]"
# 检查文件存在
[ -f "$1" ] || die "File not found: $1"
# 检查目录存在
[ -d "$2" ] || die "Directory not found: $2"
```
## 最佳实践
### 1. 始终使用 shebang
```bash
#!/bin/bash
# 或
#!/usr/bin/env bash
```
### 2. 使用 set -euo pipefail
```bash
#!/bin/bash
set -euo pipefail
```
### 3. 引用所有变量
```bash
# 除非确定变量不包含空格或通配符
echo "$var"
```
### 4. 使用 [[ ]] 而不是 [ ]
```bash
# [[ 更强大且更安全
if [[ $name == "John" ]]; then
if [[ -f $file && $size -gt 100 ]]; then
```
### 5. 使用 $(command) 而不是反引号
```bash
# $() 更易读且可嵌套
result=$(command1 $(command2))
```
### 6. 使用函数组织代码
```bash
my_function() {
local arg1=$1
local arg2=$2
# 函数体
}
my_function "value1" "value2"
```
## ShellCheck 静态分析
ShellCheck 是一个 Shell 脚本静态分析工具:
```bash
# 安装 ShellCheck
brew install shellcheck # macOS
apt install shellcheck # Ubuntu
# 使用
shellcheck script.sh
```

View File

@@ -0,0 +1,204 @@
---
name: citation-verification
description: This skill provides reference guidance for citation verification in academic writing. Use when the user asks about "citation verification best practices", "how to verify references", "preventing fake citations", or needs guidance on citation accuracy. This skill supports ml-paper-writing by providing detailed verification principles and common error patterns.
tags: [Research, Academic, Citation, Reference]
version: 0.1.0
---
# Citation Verification Reference Guide
A reference guide for citation verification in academic paper writing, providing verification principles and best practices.
**Core Principle**: Proactively verify every citation during the writing process using programmatic or canonical scholarly sources first: arXiv, DOI/CrossRef, Semantic Scholar, publisher landing pages, and Zotero metadata. Google Scholar is useful for manual discovery, but it is not the canonical verification authority.
## Core Problems
Citation issues in academic papers seriously impact research integrity:
1. **Fake citations** - Citing non-existent papers (common issue with AI-generated citations)
2. **Incorrect information** - Mismatched authors, titles, years, etc.
3. **Inconsistent formatting** - Mixed citation formats
4. **Missing citations** - Referenced but uncited work
These issues can lead to:
- Paper rejection or retraction
- Damage to academic reputation
- Reviewers questioning research rigor
**Special risk with AI-assisted writing**: AI-generated citations have approximately 40% error rate; every citation must be verified via WebSearch.
## Verification Principles
This skill provides verification principles based on canonical scholarly metadata and claim-level checking:
### 1. Proactive Verification (Verify During Writing)
**Core idea**: Verify immediately when adding a citation, rather than checking after writing is complete.
- Search for the paper via WebSearch each time a citation is needed
- Confirm the paper exists on Google Scholar
- Add to bibliography only after verification passes
### 2. Canonical Metadata Verification
Preferred authority order:
1. DOI / publisher landing page
2. arXiv ID or arXiv landing page
3. CrossRef
4. Semantic Scholar
5. Zotero metadata imported from a verified identifier
6. Google Scholar only for manual discovery or fallback lookup
**Verification steps**:
1. Find a DOI, arXiv ID, publisher URL, or verified Zotero item.
2. Confirm title, first author, year, venue, and identifier.
3. Fetch BibTeX from CrossRef, arXiv, publisher metadata, Zotero, or another programmatic source when possible.
4. If only Google Scholar can find the item, mark it as manual verification and do not treat the BibTeX as final until metadata is checked elsewhere.
### 3. Information Matching Verification
**Information that must match**:
- Title (minor differences allowed, e.g., capitalization)
- Authors (at least the first author must match)
- Year (±1 year difference allowed, considering preprints)
- Publication venue (conference/journal name)
### 4. Claim Verification
**Key principle**: When citing a specific claim, you must confirm the claim actually appears in the paper.
- Use WebSearch to access the paper PDF
- Search for relevant keywords
- Confirm the accuracy of the claim
- Record the section/page where the claim appears
## Verification Workflow
### Integration into Writing Process
```
Need a citation during writing
Find DOI / arXiv ID / publisher page / verified Zotero item
Verify metadata with CrossRef / arXiv / Semantic Scholar / publisher / Zotero
Confirm paper details
Get BibTeX
(If citing a specific claim) Verify the claim
Add to bibliography
```
**Key point**: Verification is part of the writing process, not a separate post-processing step.
## Usage Guide
### Using with ml-paper-writing
The verification principles of this skill are integrated into the Citation Workflow of the `ml-paper-writing` skill.
**Auto-trigger**: Citation verification is automatically executed when writing papers with the ml-paper-writing skill.
**Manual reference**: Refer to this skill when you need detailed verification principles.
### Verification Step Example
**Scenario**: Need to cite the Transformer paper
```
Step 1: WebSearch lookup
Query: "Attention is All You Need Vaswani 2017"
Result: Found multiple sources for the paper
Step 2: Google Scholar verification
Query: "site:scholar.google.com Attention is All You Need Vaswani"
Result: ✅ Paper exists, 50,000+ citations, NeurIPS 2017
Step 3: Confirm details
- Title: "Attention is All You Need"
- Authors: Vaswani, Ashish; Shazeer, Noam; Parmar, Niki; ...
- Year: 2017
- Venue: NeurIPS (NIPS)
Step 4: Get BibTeX
- Click "Cite" on Google Scholar
- Select BibTeX format
- Copy BibTeX entry
Step 5: Add to bibliography
- Paste into .bib file
- Use \cite{vaswani2017attention} in the paper
```
### Handling Verification Failures
**If the paper cannot be verified through canonical sources**:
1. **Check spelling** - Is the title or author name correct?
2. **Try different queries** - Use different keyword combinations
3. **Find alternative sources** - Try arXiv, DOI, CrossRef, Semantic Scholar, publisher pages, or Zotero
4. **Mark as pending** - Use `[CITATION NEEDED]` marker
5. **Notify the user** - Clearly state the citation cannot be verified
**If information doesn't match**:
1. **Confirm the source** - Did you find the correct paper?
2. **Check versions** - Preprint vs. published version
3. **Update information** - Use the most accurate version
4. **Record discrepancies** - Note the reason for differences
## Best Practices
### Preventing Fake Citations
1. **Never generate citations from memory** - AI-generated citations have 40% error rate
2. **Use WebSearch to find** - Verify every citation through WebSearch
3. **Confirm on Google Scholar** - Verify paper existence on Google Scholar
4. **Verify promptly** - Verify when adding citations, don't wait until finished
### Handling Verification Failures
1. **Don't guess** - If you can't find the paper, don't fabricate information
2. **Mark clearly** - Use `[CITATION NEEDED]` to mark explicitly
3. **Notify the user** - Clearly state which citations cannot be verified
4. **Provide reasons** - Explain why verification failed (not found, info mismatch, etc.)
### Improving Verification Accuracy
1. **Complete queries** - Include title, author, year
2. **Check citation count** - Citation count on Google Scholar is a credibility indicator
3. **Confirm venue** - Verify conference/journal name is correct
4. **Verify claims** - When citing specific claims, confirm they exist in the paper
### Common Pitfalls
**Wrong approach**:
- Generating BibTeX from memory
- Skipping Google Scholar verification
- Assuming a paper exists
- Not marking unverifiable citations
**Correct approach**:
- Search every citation with WebSearch
- Confirm on Google Scholar
- Copy BibTeX from Google Scholar
- Clearly mark unverifiable citations
## Summary
**Core Principle**: Proactively verify every citation during the writing process using WebSearch and Google Scholar.
**Key Steps**:
1. WebSearch to find the paper
2. Google Scholar to verify existence
3. Confirm details
4. Get BibTeX
5. Verify claims (if needed)
6. Add to bibliography
**Failure handling**: When verification fails, mark as `[CITATION NEEDED]` and clearly notify the user.
**Integration**: The principles of this skill are integrated into the ml-paper-writing skill for automatic verification.

View File

@@ -0,0 +1,72 @@
# Citation Verification Reference Files
## 文件用途
本目录中的文件提供**背景知识和参考信息**,用于理解引用验证的原理和常见问题。
**重要**: 这些文件不是主要工作流的一部分。实际的引用验证优先使用 arXiv、DOI/CrossRef、Semantic Scholar、publisher metadata 和 Zotero metadata。Google Scholar 只能作为人工发现或 fallback。
## 文件说明
### common-errors.md
**内容**: 常见引用错误模式和修复方法
**用途**:
- 了解学术写作中常见的引用错误
- 学习如何识别和修复这些错误
- 理解为什么需要验证引用
**何时参考**: 当需要了解引用错误的类型和修复方法时
### verification-rules.md
**内容**: 详细的验证规则和匹配算法
**用途**:
- 理解引用验证的完整逻辑
- 了解如何匹配标题、作者、年份等信息
- 学习验证的技术细节
**何时参考**: 当需要深入了解验证逻辑时
### api-usage.md
**内容**: API 使用指南CrossRef、arXiv、Semantic Scholar
**用途**:
- 了解学术API的使用方法
- 理解API验证的原理
- 参考高级用例的实现
**何时参考**: 当需要了解API验证方法时。当前主要工作流应优先使用这些 programmatic / canonical sources。
## 主要工作流
**实际的引用验证应该使用 `ml-paper-writing` skill 中的 Citation Workflow**
1. 查找 DOI、arXiv ID、publisher page 或 verified Zotero item
2. 用 CrossRef、arXiv、Semantic Scholar、publisher metadata 或 Zotero metadata 验证
3. 从 programmatic/canonical source 获取 BibTeX
4. 验证声明(如需要)
5. 添加到 bibliography
详见 `ml-paper-writing` skill 的 "Citation Workflow (Hallucination Prevention)" 部分。
## 使用建议
**对于日常论文写作**:
- ✅ 使用 `ml-paper-writing` skill 的 Citation Workflow
- ✅ 使用 arXiv、DOI/CrossRef、Semantic Scholar、publisher metadata 和 Zotero metadata
- ✅ 必要时用 Google Scholar 做人工发现,但不要把它作为 canonical authority
- ✅ 参考这些文件了解背景知识
- ❌ 不要从记忆或未经验证的 Google Scholar 条目生成最终 BibTeX
**对于理解验证原理**:
- 阅读 `common-errors.md` 了解常见错误
- 阅读 `verification-rules.md` 了解验证逻辑
- 阅读 `api-usage.md` 了解API方法参考用
## 更多信息
详见 `citation-verification` skill 的 SKILL.md 文件。

View File

@@ -0,0 +1,373 @@
# API 使用指南
本文档详细说明如何使用三个主要 API 进行文献验证。
## Semantic Scholar API
### 概述
Semantic Scholar 是一个免费的学术搜索引擎,提供强大的 API 用于论文检索和元数据获取。
**优势:**
- 免费使用,无需 API key
- 覆盖广泛的学科领域
- 提供丰富的元数据
- 支持模糊搜索
**限制:**
- 请求频率限制:100 requests/5min
- 部分论文可能缺失
### API 端点
**1. 通过 Paper ID 获取论文**
```
GET https://api.semanticscholar.org/graph/v1/paper/{paper_id}
```
**2. 搜索论文**
```
GET https://api.semanticscholar.org/graph/v1/paper/search?query={query}
```
### Python 示例
**安装:**
```bash
pip install semanticscholar
```
**基本用法:**
```python
from semanticscholar import SemanticScholar
sch = SemanticScholar()
# 通过标题搜索
results = sch.search_paper("Attention is All You Need", limit=5)
for paper in results:
print(f"Title: {paper.title}")
print(f"Authors: {[a.name for a in paper.authors]}")
print(f"Year: {paper.year}")
print(f"DOI: {paper.externalIds.get('DOI', 'N/A')}")
print("---")
```
**通过 DOI 获取:**
```python
# DOI 格式: DOI:10.48550/arXiv.1706.03762
paper = sch.get_paper("DOI:10.48550/arXiv.1706.03762")
print(f"Title: {paper.title}")
print(f"Citations: {paper.citationCount}")
```
### 字段说明
**返回的主要字段:**
- `paperId` - Semantic Scholar 内部 ID
- `title` - 论文标题
- `authors` - 作者列表
- `year` - 发表年份
- `venue` - 发表场所(会议/期刊)
- `externalIds` - 外部标识符(DOI, arXiv, PubMed 等)
- `citationCount` - 引用次数
- `abstract` - 摘要
### 错误处理
```python
try:
paper = sch.get_paper("invalid_id")
except Exception as e:
print(f"Error: {e}")
# 处理错误:标记需要人工验证
```
## arXiv API
### 概述
arXiv 是预印本论文库,提供免费的 API 用于访问论文元数据。
**优势:**
- 完全免费,无需认证
- 覆盖物理、数学、计算机科学等领域
- 提供完整的论文 PDF
- 更新及时
**限制:**
- 仅限预印本论文
- 不包含已发表的期刊版本信息
### API 端点
**查询接口:**
```
GET http://export.arxiv.org/api/query?search_query={query}&start={start}&max_results={max}
```
### Python 示例
**安装:**
```bash
pip install arxiv
```
**基本用法:**
```python
import arxiv
# 通过 arXiv ID 获取
paper = next(arxiv.Search(id_list=["1706.03762"]).results())
print(f"Title: {paper.title}")
print(f"Authors: {[a.name for a in paper.authors]}")
print(f"Published: {paper.published}")
print(f"PDF URL: {paper.pdf_url}")
# 通过标题搜索
search = arxiv.Search(
query="Attention is All You Need",
max_results=5,
sort_by=arxiv.SortCriterion.Relevance
)
for result in search.results():
print(f"Title: {result.title}")
print(f"arXiv ID: {result.entry_id.split('/')[-1]}")
print("---")
```
### arXiv ID 格式
**识别 arXiv ID:**
- 新格式: `YYMM.NNNNN` (如 2301.12345)
- 旧格式: `arch-ive/YYMMNNN` (如 cs/0703001)
**从 URL 提取:**
```python
import re
def extract_arxiv_id(text):
# 匹配新格式
match = re.search(r'\d{4}\.\d{4,5}', text)
if match:
return match.group()
# 匹配旧格式
match = re.search(r'[a-z-]+/\d{7}', text)
if match:
return match.group()
return None
```
## CrossRef API
### 概述
CrossRef 是 DOI 注册机构,提供权威的学术文献元数据。
**优势:**
- DOI 是最可靠的唯一标识符
- 覆盖几乎所有正式发表的论文
- 数据质量高,权威性强
- 支持 BibTeX 格式直接获取
**限制:**
- 仅限有 DOI 的论文
- 预印本通常没有 DOI
### API 端点
**通过 DOI 获取元数据:**
```
GET https://api.crossref.org/works/{doi}
```
**通过 DOI 获取 BibTeX:**
```
GET https://doi.org/{doi}
Headers: Accept: application/x-bibtex
```
### Python 示例
**通过 DOI 获取元数据:**
```python
import requests
def get_crossref_metadata(doi):
url = f"https://api.crossref.org/works/{doi}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return data['message']
return None
# 示例
doi = "10.48550/arXiv.1706.03762"
metadata = get_crossref_metadata(doi)
if metadata:
print(f"Title: {metadata['title'][0]}")
print(f"Authors: {[f\"{a['given']} {a['family']}\" for a in metadata['author']]}")
print(f"Published: {metadata['published']['date-parts'][0]}")
```
**通过 DOI 获取 BibTeX:**
```python
def doi_to_bibtex(doi):
url = f"https://doi.org/{doi}"
headers = {"Accept": "application/x-bibtex"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
# 示例
bibtex = doi_to_bibtex("10.48550/arXiv.1706.03762")
print(bibtex)
```
### DOI 格式
**标准格式:**
- `10.XXXX/suffix` (如 10.1038/nature12345)
- 前缀 `10.` 是固定的
- 中间是注册机构代码
- 后缀是出版商定义的
**从文本中提取 DOI:**
```python
import re
def extract_doi(text):
# 匹配 DOI 格式
match = re.search(r'10\.\d{4,}/[^\s]+', text)
if match:
return match.group()
return None
```
## API 选择策略
根据引用信息选择最合适的 API:
### 决策流程
```
有 DOI?
├─ 是 → CrossRef API (最可靠)
└─ 否 → 有 arXiv ID?
├─ 是 → arXiv API
└─ 否 → Semantic Scholar API (通用搜索)
```
### 实现示例
```python
def verify_citation(citation_info):
"""
根据引用信息选择合适的 API 进行验证
Args:
citation_info: dict with keys: doi, arxiv_id, title, authors
Returns:
验证结果字典
"""
# 策略 1: DOI 优先
if citation_info.get('doi'):
return verify_with_crossref(citation_info['doi'])
# 策略 2: arXiv ID
if citation_info.get('arxiv_id'):
return verify_with_arxiv(citation_info['arxiv_id'])
# 策略 3: 通用搜索
if citation_info.get('title'):
return verify_with_semantic_scholar(
citation_info['title'],
citation_info.get('authors')
)
return {'status': 'insufficient_info'}
```
## 最佳实践
### 1. 错误处理
```python
import time
from requests.exceptions import RequestException
def api_call_with_retry(func, max_retries=3):
"""带重试的 API 调用"""
for i in range(max_retries):
try:
return func()
except RequestException as e:
if i == max_retries - 1:
raise
time.sleep(2 ** i) # 指数退避
```
### 2. 速率限制
```python
import time
class RateLimiter:
def __init__(self, calls_per_minute):
self.calls_per_minute = calls_per_minute
self.last_call = 0
def wait_if_needed(self):
elapsed = time.time() - self.last_call
min_interval = 60.0 / self.calls_per_minute
if elapsed < min_interval:
time.sleep(min_interval - elapsed)
self.last_call = time.time()
# 使用示例
limiter = RateLimiter(calls_per_minute=20)
limiter.wait_if_needed()
result = api_call()
```
### 3. 缓存结果
```python
import json
from pathlib import Path
class APICache:
def __init__(self, cache_dir=".cache"):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
def get(self, key):
cache_file = self.cache_dir / f"{key}.json"
if cache_file.exists():
return json.loads(cache_file.read_text())
return None
def set(self, key, value):
cache_file = self.cache_dir / f"{key}.json"
cache_file.write_text(json.dumps(value))
```
## 总结
### API 对比
| API | 优势 | 限制 | 推荐场景 |
|-----|------|------|----------|
| **CrossRef** | 最权威,支持 BibTeX | 仅限有 DOI 的论文 | 有 DOI 时首选 |
| **arXiv** | 免费,更新快 | 仅限预印本 | arXiv 论文 |
| **Semantic Scholar** | 覆盖广,模糊搜索 | 部分论文缺失 | 通用搜索 |
### 验证可靠性排序
1. **CrossRef (DOI)** - 最可靠
2. **arXiv (arXiv ID)** - 可靠
3. **Semantic Scholar (标题搜索)** - 较可靠,需要人工确认

View File

@@ -0,0 +1,385 @@
# 常见引用错误模式
本文档总结常见的引用错误类型、识别方法和修复建议。
## 错误分类
### 1. 格式错误 (Format Errors)
#### 1.1 缺少必填字段
**错误示例:**
```bibtex
@article{smith2020,
title={Deep Learning for NLP},
year={2020}
}
```
**问题:** 缺少 `author``journal` 字段
**修复:**
```bibtex
@article{smith2020,
author={Smith, John and Doe, Jane},
title={Deep Learning for NLP},
journal={Nature},
year={2020}
}
```
#### 1.2 年份格式错误
**错误示例:**
```bibtex
year={20} # 年份不完整
year={2020-2021} # 年份范围格式错误
year={circa 2020} # 包含非数字字符
```
**修复:**
```bibtex
year={2020} # 使用四位数年份
```
#### 1.3 DOI 格式错误
**错误示例:**
```bibtex
doi={doi:10.1038/nature12345} # 包含 "doi:" 前缀
doi={https://doi.org/10.1038/...} # 包含完整 URL
doi={10.1038/nature12345.} # 末尾有句号
```
**修复:**
```bibtex
doi={10.1038/nature12345} # 只保留 DOI 本身
```
#### 1.4 作者名格式不一致
**错误示例:**
```bibtex
author={John Smith and Jane Doe and Bob} # 格式不一致
author={Smith, J. and Doe, Jane} # 格式混用
```
**修复:**
```bibtex
author={Smith, John and Doe, Jane and Brown, Bob} # 统一格式
# 或
author={Smith, J. and Doe, J. and Brown, B.} # 统一缩写
```
### 2. 信息错误 (Information Errors)
#### 2.1 作者名拼写错误
**错误示例:**
```bibtex
author={Vaswani, Ashish} # 正确
author={Vaswani, Asish} # 拼写错误
```
**识别方法:**
- API 验证时作者匹配度低
- 通过 Google Scholar 搜索确认正确拼写
**修复建议:**
- 从可靠来源(Google Scholar, Semantic Scholar)获取 BibTeX
- 仔细核对作者名拼写
#### 2.2 标题错误
**错误示例:**
```bibtex
title={Attention is All You Need} # 正确
title={Attention Is All You Need} # 大小写错误
title={Attention is all you need} # 大小写错误
title={Attention Mechanism for Transformers} # 标题完全错误
```
**识别方法:**
- 标题匹配度低于阈值
- API 返回的标题与 BibTeX 中的标题不一致
**修复建议:**
- 从原始论文或 DOI 获取准确标题
- 保持原始大小写格式
#### 2.3 年份错误
**常见情况:**
- 使用预印本年份而非正式发表年份
- 使用会议年份而非论文集出版年份
**错误示例:**
```bibtex
# 论文在 2017 年 arXiv 发布,2018 年 NIPS 正式发表
year={2017} # 使用了预印本年份
year={2018} # 正确:使用正式发表年份
```
**修复建议:**
- 优先使用正式发表年份
- 如果引用预印本,在 note 字段说明
#### 2.4 期刊/会议名称错误
**错误示例:**
```bibtex
booktitle={NeurIPS} # 缩写
booktitle={Neural Information Processing Systems} # 完整名称
booktitle={Advances in Neural Information Processing Systems} # 正确的完整名称
```
**修复建议:**
- 使用官方全称或标准缩写
- 保持整个文献列表的命名一致性
### 3. 虚假引用 (Fake Citations)
#### 3.1 完全虚构的论文
**特征:**
- 论文不存在于任何数据库
- API 验证全部失败
- 无法通过 Google Scholar 找到
**识别方法:**
```python
# 所有 API 都返回 not_found
if not crossref_found and not arxiv_found and not semantic_scholar_found:
return "可能是虚假引用"
```
**修复建议:**
- 删除虚假引用
- 如果确实需要引用,寻找真实的相关论文
#### 3.2 信息严重错误的引用
**特征:**
- 论文存在,但信息完全不匹配
- 作者、标题、年份都不对
- 可能是复制粘贴错误
**错误示例:**
```bibtex
@article{smith2020deep,
author={Smith, John},
title={Deep Learning for NLP},
journal={Nature},
year={2020}
}
```
**实际论文:**
- 作者: Brown, Tom et al.
- 标题: Language Models are Few-Shot Learners
- 期刊: NeurIPS
- 年份: 2020
**修复建议:**
- 重新搜索正确的论文
- 从可靠来源获取正确的 BibTeX
#### 3.3 引用不存在的版本
**错误示例:**
```bibtex
# 引用了不存在的期刊版本
@article{vaswani2017attention,
author={Vaswani, Ashish and others},
title={Attention is All You Need},
journal={Nature Machine Intelligence}, # :
year={2017}
}
```
**正确引用:**
```bibtex
@inproceedings{vaswani2017attention,
author={Vaswani, Ashish and others},
title={Attention is All You Need},
booktitle={Advances in Neural Information Processing Systems},
year={2017}
}
```
### 4. 一致性错误 (Consistency Errors)
#### 4.1 LaTeX 引用与 BibTeX 不一致
**错误示例:**
LaTeX 文件中:
```latex
\cite{smith2020deep}
```
BibTeX 文件中:
```bibtex
@article{smith2020deeplearning, # Key
author={Smith, John},
title={Deep Learning for NLP},
year={2020}
}
```
**识别方法:**
```python
def check_citation_consistency(tex_keys, bib_keys):
"""检查引用一致性"""
tex_set = set(tex_keys)
bib_set = set(bib_keys)
# 未定义的引用
undefined = tex_set - bib_set
# 未使用的引用
unused = bib_set - tex_set
return {
'undefined': list(undefined),
'unused': list(unused)
}
```
**修复建议:**
- 确保 LaTeX 中的 citation key 与 BibTeX 中的 ID 完全一致
- 删除未使用的 BibTeX 条目
- 补充缺失的 BibTeX 条目
#### 4.2 引用格式不统一
**错误示例:**
```bibtex
# 同一文献列表中格式混乱
@article{paper1,
author={Smith, John and Doe, Jane}, #
...
}
@article{paper2,
author={Brown, T. and Lee, S.}, #
...
}
@article{paper3,
author={John Wilson and Mary Johnson}, # First Last
...
}
```
**修复建议:**
- 统一作者名格式(全名或缩写)
- 统一期刊/会议名称格式(全称或标准缩写)
- 统一页码格式(1-10 或 1--10)
#### 4.3 重复引用
**错误示例:**
```bibtex
@article{vaswani2017,
author={Vaswani, Ashish and others},
title={Attention is All You Need},
booktitle={NeurIPS},
year={2017}
}
@inproceedings{vaswani2017attention,
author={Vaswani, A. and others},
title={Attention is All You Need},
booktitle={Advances in Neural Information Processing Systems},
year={2017}
}
```
**问题:** 同一篇论文被引用两次,使用不同的 citation key
**识别方法:**
- 标题高度相似(相似度 > 0.9)
- 作者重叠度高
- 年份相同
**修复建议:**
- 保留更完整准确的条目
- 删除重复条目
- 更新 LaTeX 文件中的引用
## 错误预防最佳实践
### 1. 使用可靠来源
**推荐来源:**
- Google Scholar - 获取 BibTeX
- Semantic Scholar - 验证论文信息
- 官方出版商网站 - 获取准确元数据
- DOI 系统 - 最可靠的标识符
**避免:**
- 手动输入 BibTeX
- 从不可靠网站复制
- 使用过时的引用管理工具
### 2. 及时验证
**验证时机:**
- 添加引用后立即验证
- 完成初稿后全面验证
- 提交前最终验证
**验证内容:**
- 格式完整性
- 信息准确性
- 引用一致性
### 3. 保持一致性
**统一标准:**
- 作者名格式统一(全名或缩写)
- 期刊/会议名称统一(全称或标准缩写)
- 页码格式统一
- 大小写规则统一
### 4. 使用工具辅助
**推荐工具:**
- BibTeX 格式检查器
- LaTeX 编译器(检测未定义引用)
- Citation verification scripts
- 引用管理软件(Zotero, Mendeley)
## 常见错误总结
| 错误类型 | 严重程度 | 检测难度 | 修复难度 |
|---------|---------|---------|---------|
| 缺少必填字段 | 高 | 低 | 低 |
| 年份格式错误 | 中 | 低 | 低 |
| DOI 格式错误 | 中 | 低 | 低 |
| 作者名拼写错误 | 高 | 中 | 中 |
| 标题错误 | 高 | 中 | 中 |
| 完全虚构论文 | 极高 | 高 | 高 |
| 信息严重错误 | 极高 | 中 | 高 |
| LaTeX-BibTeX 不一致 | 高 | 低 | 低 |
| 格式不统一 | 低 | 低 | 中 |
| 重复引用 | 中 | 中 | 中 |
## 快速检查清单
提交论文前,确保完成以下检查:
- [ ] 所有 BibTeX 条目包含必填字段
- [ ] 年份格式正确(四位数字)
- [ ] DOI 格式正确(无前缀,无 URL)
- [ ] 作者名格式统一
- [ ] 标题大小写正确
- [ ] 所有引用通过 API 验证
- [ ] LaTeX 引用与 BibTeX 一致
- [ ] 无重复引用
- [ ] 格式统一(作者名、期刊名、页码)
- [ ] 无虚假或严重错误的引用
遵循这些最佳实践可以有效避免常见的引用错误,提高论文质量和可信度。

View File

@@ -0,0 +1,400 @@
# 验证规则
本文档详细说明四层验证机制的具体规则和匹配算法。
## Layer 1: Format Validation (格式验证)
### BibTeX 格式检查
**必填字段验证:**
不同类型的 BibTeX 条目有不同的必填字段要求:
**@article (期刊论文):**
- 必填: `author`, `title`, `journal`, `year`
- 可选: `volume`, `number`, `pages`, `doi`
**@inproceedings (会议论文):**
- 必填: `author`, `title`, `booktitle`, `year`
- 可选: `pages`, `organization`, `doi`
**@book (书籍):**
- 必填: `author``editor`, `title`, `publisher`, `year`
- 可选: `volume`, `series`, `address`
**@misc (其他):**
- 必填: `title`
- 可选: `author`, `howpublished`, `year`, `note`
### 格式检查规则
**1. 条目结构检查**
```python
def check_bibtex_structure(entry):
"""检查 BibTeX 条目结构"""
errors = []
# 检查是否有类型
if not entry.get('ENTRYTYPE'):
errors.append("Missing entry type")
# 检查是否有 ID
if not entry.get('ID'):
errors.append("Missing citation key")
# 检查必填字段
required = get_required_fields(entry.get('ENTRYTYPE'))
for field in required:
if not entry.get(field):
errors.append(f"Missing required field: {field}")
return errors
```
**2. 字段格式检查**
```python
def check_field_format(entry):
"""检查字段格式"""
errors = []
# 年份格式检查
if 'year' in entry:
year = entry['year']
if not year.isdigit() or len(year) != 4:
errors.append(f"Invalid year format: {year}")
if int(year) < 1900 or int(year) > 2030:
errors.append(f"Year out of reasonable range: {year}")
# DOI 格式检查
if 'doi' in entry:
doi = entry['doi']
if not doi.startswith('10.'):
errors.append(f"Invalid DOI format: {doi}")
return errors
```
### LaTeX 引用检查
**1. 引用命令检查**
```python
def check_latex_citations(tex_content):
"""检查 LaTeX 引用命令"""
import re
# 查找所有引用命令
cite_pattern = r'\\cite(?:\[[^\]]*\])?\{([^}]+)\}'
citations = re.findall(cite_pattern, tex_content)
# 展开多个引用
all_keys = []
for cite in citations:
keys = [k.strip() for k in cite.split(',')]
all_keys.extend(keys)
return all_keys
```
**2. 引用一致性检查**
```python
def check_citation_consistency(tex_keys, bib_keys):
"""检查引用一致性"""
tex_set = set(tex_keys)
bib_set = set(bib_keys)
# 未定义的引用
undefined = tex_set - bib_set
# 未使用的引用
unused = bib_set - tex_set
return {
'undefined': list(undefined),
'unused': list(unused)
}
```
## Layer 2: Existence Verification (存在性验证)
### API 验证流程
**验证步骤:**
1. 根据引用信息选择 API (DOI → CrossRef, arXiv ID → arXiv, 其他 → Semantic Scholar)
2. 调用 API 获取论文信息
3. 判断论文是否存在
**验证结果:**
- `exists` - 论文存在
- `not_found` - 论文不存在
- `api_error` - API 调用失败,需要人工验证
### 验证代码示例
```python
def verify_existence(citation_info):
"""验证论文存在性"""
# DOI 优先
if citation_info.get('doi'):
result = verify_with_crossref(citation_info['doi'])
if result['status'] == 'success':
return {'exists': True, 'source': 'crossref', 'data': result['data']}
# arXiv ID
if citation_info.get('arxiv_id'):
result = verify_with_arxiv(citation_info['arxiv_id'])
if result['status'] == 'success':
return {'exists': True, 'source': 'arxiv', 'data': result['data']}
# 通用搜索
if citation_info.get('title'):
result = verify_with_semantic_scholar(citation_info['title'])
if result['status'] == 'success' and result['data']:
return {'exists': True, 'source': 'semantic_scholar', 'data': result['data']}
return {'exists': False, 'source': None}
```
## Layer 3: Information Matching (信息匹配)
### 匹配算法
**1. 标题匹配**
使用模糊匹配算法,允许轻微差异:
```python
from difflib import SequenceMatcher
def match_title(title1, title2, threshold=0.85):
"""标题匹配"""
# 标准化:小写、去除标点
def normalize(text):
import re
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
return ' '.join(text.split())
t1 = normalize(title1)
t2 = normalize(title2)
# 计算相似度
ratio = SequenceMatcher(None, t1, t2).ratio()
return {
'match': ratio >= threshold,
'similarity': ratio
}
```
**2. 作者匹配**
考虑作者顺序和名字格式差异:
```python
def match_authors(authors1, authors2, threshold=0.7):
"""作者匹配"""
def normalize_name(name):
# 处理 "Last, First" 和 "First Last" 格式
parts = name.replace(',', '').split()
return ' '.join(sorted(parts)).lower()
names1 = [normalize_name(a) for a in authors1]
names2 = [normalize_name(a) for a in authors2]
# 计算交集比例
set1 = set(names1)
set2 = set(names2)
intersection = len(set1 & set2)
union = len(set1 | set2)
if union == 0:
return {'match': False, 'similarity': 0}
ratio = intersection / union
return {
'match': ratio >= threshold,
'similarity': ratio
}
```
**3. 年份匹配**
允许 ±1 年的差异(考虑预印本和正式发表的时间差):
```python
def match_year(year1, year2, tolerance=1):
"""年份匹配"""
try:
y1 = int(year1)
y2 = int(year2)
diff = abs(y1 - y2)
return {
'match': diff <= tolerance,
'difference': diff
}
except (ValueError, TypeError):
return {'match': False, 'difference': None}
```
## Layer 4: Content Validation (内容验证)
### 综合匹配评分
综合所有匹配结果,计算总体匹配分数:
```python
def calculate_match_score(citation, api_data):
"""计算综合匹配分数"""
scores = {}
weights = {
'title': 0.4,
'authors': 0.3,
'year': 0.2,
'venue': 0.1
}
# 标题匹配
if citation.get('title') and api_data.get('title'):
result = match_title(citation['title'], api_data['title'])
scores['title'] = result['similarity']
# 作者匹配
if citation.get('authors') and api_data.get('authors'):
result = match_authors(citation['authors'], api_data['authors'])
scores['authors'] = result['similarity']
# 年份匹配
if citation.get('year') and api_data.get('year'):
result = match_year(citation['year'], api_data['year'])
scores['year'] = 1.0 if result['match'] else 0.0
# 计算加权总分
total_score = 0
total_weight = 0
for key, weight in weights.items():
if key in scores:
total_score += scores[key] * weight
total_weight += weight
if total_weight == 0:
return 0
return total_score / total_weight
```
### 验证结果判定
根据匹配分数判定验证结果:
```python
def judge_verification_result(match_score):
"""判定验证结果"""
if match_score >= 0.9:
return {
'status': 'verified',
'level': 'high_confidence',
'message': '✅ 验证通过 - 信息完全匹配'
}
elif match_score >= 0.7:
return {
'status': 'partial_match',
'level': 'medium_confidence',
'message': '⚠️ 部分匹配 - 信息有轻微差异,建议人工确认'
}
elif match_score >= 0.5:
return {
'status': 'low_match',
'level': 'low_confidence',
'message': '❌ 匹配度低 - 信息差异较大,需要人工验证'
}
else:
return {
'status': 'failed',
'level': 'no_confidence',
'message': '❌ 验证失败 - 信息严重不匹配或论文不存在'
}
```
## 完整验证流程
### 主验证函数
```python
def verify_citation_complete(citation):
"""完整的引用验证流程"""
result = {
'citation_key': citation.get('ID'),
'layers': {}
}
# Layer 1: 格式验证
format_errors = check_bibtex_structure(citation)
format_errors.extend(check_field_format(citation))
result['layers']['format'] = {
'passed': len(format_errors) == 0,
'errors': format_errors
}
# Layer 2: 存在性验证
existence = verify_existence(citation)
result['layers']['existence'] = existence
if not existence['exists']:
result['final_status'] = 'not_found'
return result
# Layer 3 & 4: 信息匹配和内容验证
api_data = existence['data']
match_score = calculate_match_score(citation, api_data)
judgment = judge_verification_result(match_score)
result['layers']['matching'] = {
'score': match_score,
'judgment': judgment
}
result['final_status'] = judgment['status']
result['confidence'] = judgment['level']
return result
```
## 验证阈值配置
### 可调整的阈值参数
```python
VERIFICATION_THRESHOLDS = {
# 匹配阈值
'title_similarity': 0.85, # 标题相似度阈值
'author_similarity': 0.70, # 作者相似度阈值
'year_tolerance': 1, # 年份容差
# 判定阈值
'high_confidence': 0.90, # 高置信度阈值
'medium_confidence': 0.70, # 中等置信度阈值
'low_confidence': 0.50, # 低置信度阈值
# 权重配置
'weights': {
'title': 0.4,
'authors': 0.3,
'year': 0.2,
'venue': 0.1
}
}
```
### 阈值调整建议
**严格模式** (用于正式发表):
- title_similarity: 0.90
- author_similarity: 0.80
- high_confidence: 0.95
**宽松模式** (用于初稿):
- title_similarity: 0.80
- author_similarity: 0.60
- high_confidence: 0.85

View File

@@ -0,0 +1,81 @@
# Citation Verification Scripts
## 状态说明
**这些脚本是参考实现,不是主要工作流的一部分。**
本目录中的Python脚本提供了基于API的引用验证实现但**实际的引用验证工作流使用WebSearch和Google Scholar**,而不是这些脚本。
## 为什么保留这些脚本?
这些脚本作为**参考实现**保留,用于:
1. **理解验证逻辑** - 展示引用验证的完整逻辑和步骤
2. **学习API使用** - 了解如何使用CrossRef、arXiv、Semantic Scholar等API
3. **高级用例** - 对于需要批量验证或自动化的场景,可以参考这些实现
## 主要工作流
**实际的引用验证应该使用 `ml-paper-writing` skill 中的 Citation Workflow**
1. 使用 WebSearch 查找论文
2. 在 Google Scholar 上验证
3. 从 Google Scholar 获取 BibTeX
4. 验证声明(如需要)
5. 添加到 bibliography
详见 `ml-paper-writing` skill 的 "Citation Workflow (Hallucination Prevention)" 部分。
## 脚本说明
### verify-citations.py
完整的引用验证脚本,包含:
- 四层验证机制(格式、存在性、信息匹配、内容验证)
- 多API支持CrossRef、arXiv、Semantic Scholar
- 报告生成
**用途**: 参考实现,了解完整的验证逻辑
### api-clients.py
API客户端库包含
- CrossRefClient - DOI验证
- ArXivClient - arXiv论文验证
- SemanticScholarClient - 通用学术搜索
- CitationAPIManager - 统一API管理
**用途**: 参考实现了解如何使用学术API
### format-checker.py
BibTeX和LaTeX格式检查工具包含
- BibTeX格式验证
- LaTeX引用检查
- 格式错误报告
**用途**: 参考实现,了解格式检查逻辑
## 使用建议
**对于日常论文写作**:
- ✅ 使用 `ml-paper-writing` skill 的 Citation Workflow
- ✅ 使用 WebSearch 和 Google Scholar
- ❌ 不要使用这些Python脚本
**对于批量验证或自动化**:
- 可以参考这些脚本的实现
- 根据需要修改和使用
- 注意API速率限制
## 依赖安装
如果需要运行这些脚本(仅用于参考或高级用例):
```bash
pip install bibtexparser requests semanticscholar arxiv
```
## 更多信息
详见 `citation-verification` skill 的 SKILL.md 文件。

View File

@@ -0,0 +1,542 @@
#!/usr/bin/env python3
"""
API Clients for Citation Verification
提供三个主要 API 客户端:
1. CrossRefClient - DOI 验证
2. ArXivClient - arXiv 论文验证
3. SemanticScholarClient - 通用学术搜索
每个客户端都包含:
- 错误处理
- 重试机制
- 速率限制
- 结果标准化
"""
import time
import requests
from typing import Dict, List, Optional
from abc import ABC, abstractmethod
class RateLimiter:
"""速率限制器"""
def __init__(self, calls_per_minute: int):
self.calls_per_minute = calls_per_minute
self.last_call = 0
self.min_interval = 60.0 / calls_per_minute
def wait_if_needed(self):
"""如果需要,等待以满足速率限制"""
elapsed = time.time() - self.last_call
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
self.last_call = time.time()
class APIClient(ABC):
"""API 客户端基类"""
def __init__(self, rate_limit: int = 20):
"""
Args:
rate_limit: 每分钟最大请求数
"""
self.rate_limiter = RateLimiter(rate_limit)
@abstractmethod
def search(self, **kwargs) -> Optional[Dict]:
"""搜索论文"""
pass
def _retry_request(self, func, max_retries: int = 3):
"""带重试的请求"""
for i in range(max_retries):
try:
self.rate_limiter.wait_if_needed()
return func()
except requests.exceptions.RequestException as e:
if i == max_retries - 1:
raise
time.sleep(2 ** i) # 指数退避
return None
class CrossRefClient(APIClient):
"""CrossRef API 客户端
用于通过 DOI 验证论文信息
API 文档: https://api.crossref.org/
"""
def __init__(self, rate_limit: int = 50):
"""
Args:
rate_limit: 每分钟最大请求数 (CrossRef 限制较宽松)
"""
super().__init__(rate_limit)
self.base_url = "https://api.crossref.org"
def search_by_doi(self, doi: str) -> Optional[Dict]:
"""通过 DOI 搜索论文
Args:
doi: DOI 标识符 (如 10.1038/nature12345)
Returns:
标准化的论文信息字典,如果未找到则返回 None
"""
def request():
url = f"{self.base_url}/works/{doi}"
response = requests.get(url, timeout=10)
response.raise_for_status()
return response.json()
try:
data = self._retry_request(request)
if data and 'message' in data:
return self._normalize_result(data['message'])
return None
except Exception as e:
print(f"CrossRef API 错误: {e}")
return None
def search(self, doi: str = None, **kwargs) -> Optional[Dict]:
"""搜索论文 (统一接口)"""
if doi:
return self.search_by_doi(doi)
return None
def _normalize_result(self, data: Dict) -> Dict:
"""标准化 CrossRef 返回结果"""
# 提取标题
title = data.get('title', [''])[0] if 'title' in data else ''
# 提取作者
authors = []
if 'author' in data:
for author in data['author']:
given = author.get('given', '')
family = author.get('family', '')
if given and family:
authors.append(f"{given} {family}")
elif family:
authors.append(family)
# 提取年份
year = None
if 'published' in data:
date_parts = data['published'].get('date-parts', [[]])[0]
if date_parts:
year = date_parts[0]
elif 'created' in data:
date_parts = data['created'].get('date-parts', [[]])[0]
if date_parts:
year = date_parts[0]
# 提取期刊/会议名称
venue = ''
if 'container-title' in data:
venue = data['container-title'][0] if data['container-title'] else ''
return {
'title': title,
'authors': authors,
'year': year,
'venue': venue,
'doi': data.get('DOI', ''),
'type': data.get('type', ''),
'source': 'crossref'
}
def get_bibtex(self, doi: str) -> Optional[str]:
"""通过 DOI 获取 BibTeX
Args:
doi: DOI 标识符
Returns:
BibTeX 字符串,如果失败则返回 None
"""
def request():
url = f"https://doi.org/{doi}"
headers = {"Accept": "application/x-bibtex"}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return response.text
try:
return self._retry_request(request)
except Exception as e:
print(f"获取 BibTeX 失败: {e}")
return None
class ArXivClient(APIClient):
"""arXiv API 客户端
用于验证 arXiv 预印本论文
API 文档: https://info.arxiv.org/help/api/
"""
def __init__(self, rate_limit: int = 20):
"""
Args:
rate_limit: 每分钟最大请求数
"""
super().__init__(rate_limit)
try:
import arxiv
self.arxiv = arxiv
except ImportError:
raise ImportError("需要安装 arxiv 库: pip install arxiv")
def search_by_id(self, arxiv_id: str) -> Optional[Dict]:
"""通过 arXiv ID 搜索论文
Args:
arxiv_id: arXiv 标识符 (如 2301.12345 或 cs/0703001)
Returns:
标准化的论文信息字典,如果未找到则返回 None
"""
def request():
search = self.arxiv.Search(id_list=[arxiv_id])
paper = next(search.results())
return paper
try:
self.rate_limiter.wait_if_needed()
paper = request()
return self._normalize_result(paper)
except StopIteration:
print(f"arXiv 论文未找到: {arxiv_id}")
return None
except Exception as e:
print(f"arXiv API 错误: {e}")
return None
def search_by_title(self, title: str, max_results: int = 5) -> Optional[Dict]:
"""通过标题搜索论文
Args:
title: 论文标题
max_results: 最大返回结果数
Returns:
标准化的论文信息字典(第一个结果),如果未找到则返回 None
"""
def request():
search = self.arxiv.Search(
query=f'ti:"{title}"',
max_results=max_results,
sort_by=self.arxiv.SortCriterion.Relevance
)
results = list(search.results())
return results[0] if results else None
try:
self.rate_limiter.wait_if_needed()
paper = request()
if paper:
return self._normalize_result(paper)
return None
except Exception as e:
print(f"arXiv API 错误: {e}")
return None
def search(self, arxiv_id: str = None, title: str = None, **kwargs) -> Optional[Dict]:
"""搜索论文 (统一接口)"""
if arxiv_id:
return self.search_by_id(arxiv_id)
elif title:
return self.search_by_title(title)
return None
def _normalize_result(self, paper) -> Dict:
"""标准化 arXiv 返回结果"""
# 提取 arXiv ID
arxiv_id = paper.entry_id.split('/')[-1]
return {
'title': paper.title,
'authors': [a.name for a in paper.authors],
'year': paper.published.year,
'venue': 'arXiv',
'arxiv_id': arxiv_id,
'doi': paper.doi if hasattr(paper, 'doi') else None,
'abstract': paper.summary,
'pdf_url': paper.pdf_url,
'source': 'arxiv'
}
@staticmethod
def extract_arxiv_id(text: str) -> Optional[str]:
"""从文本中提取 arXiv ID
Args:
text: 包含 arXiv ID 的文本
Returns:
arXiv ID,如果未找到则返回 None
"""
import re
# 匹配新格式: YYMM.NNNNN
match = re.search(r'\d{4}\.\d{4,5}', text)
if match:
return match.group()
# 匹配旧格式: arch-ive/YYMMNNN
match = re.search(r'[a-z-]+/\d{7}', text)
if match:
return match.group()
return None
class SemanticScholarClient(APIClient):
"""Semantic Scholar API 客户端
用于通用学术论文搜索和验证
API 文档: https://api.semanticscholar.org/api-docs/
"""
def __init__(self, rate_limit: int = 20):
"""
Args:
rate_limit: 每分钟最大请求数 (Semantic Scholar 限制: 100 requests/5min)
"""
super().__init__(rate_limit)
try:
from semanticscholar import SemanticScholar
self.sch = SemanticScholar()
except ImportError:
raise ImportError("需要安装 semanticscholar 库: pip install semanticscholar")
def search_by_title(self, title: str, max_results: int = 5) -> Optional[Dict]:
"""通过标题搜索论文
Args:
title: 论文标题
max_results: 最大返回结果数
Returns:
标准化的论文信息字典(第一个结果),如果未找到则返回 None
"""
try:
self.rate_limiter.wait_if_needed()
results = self.sch.search_paper(title, limit=max_results)
if not results:
return None
# 返回第一个结果
paper = results[0]
return self._normalize_result(paper)
except Exception as e:
print(f"Semantic Scholar API 错误: {e}")
return None
def search_by_doi(self, doi: str) -> Optional[Dict]:
"""通过 DOI 搜索论文
Args:
doi: DOI 标识符
Returns:
标准化的论文信息字典,如果未找到则返回 None
"""
try:
self.rate_limiter.wait_if_needed()
paper = self.sch.get_paper(f"DOI:{doi}")
if paper:
return self._normalize_result(paper)
return None
except Exception as e:
print(f"Semantic Scholar API 错误: {e}")
return None
def search(self, title: str = None, doi: str = None, **kwargs) -> Optional[Dict]:
"""搜索论文 (统一接口)"""
if doi:
return self.search_by_doi(doi)
elif title:
return self.search_by_title(title)
return None
def _normalize_result(self, paper) -> Dict:
"""标准化 Semantic Scholar 返回结果"""
# 提取作者
authors = []
if paper.authors:
authors = [a.name for a in paper.authors]
# 提取外部 ID
external_ids = paper.externalIds if hasattr(paper, 'externalIds') else {}
doi = external_ids.get('DOI') if external_ids else None
arxiv_id = external_ids.get('ArXiv') if external_ids else None
return {
'title': paper.title,
'authors': authors,
'year': paper.year,
'venue': paper.venue if hasattr(paper, 'venue') else '',
'paperId': paper.paperId,
'doi': doi,
'arxiv_id': arxiv_id,
'citationCount': paper.citationCount if hasattr(paper, 'citationCount') else 0,
'abstract': paper.abstract if hasattr(paper, 'abstract') else '',
'source': 'semantic_scholar'
}
class CitationAPIManager:
"""统一的 API 管理器
协调三个 API 客户端,实现智能的 API 选择策略
"""
def __init__(self):
"""初始化所有 API 客户端"""
self.crossref = None
self.arxiv = None
self.semantic_scholar = None
# 尝试初始化各个客户端
try:
self.crossref = CrossRefClient()
except Exception as e:
print(f"警告: CrossRef 客户端初始化失败: {e}")
try:
self.arxiv = ArXivClient()
except Exception as e:
print(f"警告: arXiv 客户端初始化失败: {e}")
try:
self.semantic_scholar = SemanticScholarClient()
except Exception as e:
print(f"警告: Semantic Scholar 客户端初始化失败: {e}")
def verify_citation(self, citation_info: Dict) -> tuple[bool, Optional[str], Optional[Dict]]:
"""验证引用
实现 API 选择策略:
1. DOI 优先 → CrossRef
2. arXiv ID → arXiv
3. 标题搜索 → Semantic Scholar
Args:
citation_info: 引用信息字典,可能包含 doi, arxiv_id, title, authors 等字段
Returns:
(exists, api_source, api_data)
- exists: 论文是否存在
- api_source: 验证来源 ('crossref', 'arxiv', 'semantic_scholar')
- api_data: API 返回的标准化数据
"""
# 策略 1: DOI 优先
if 'doi' in citation_info and self.crossref:
data = self.crossref.search_by_doi(citation_info['doi'])
if data:
return True, 'crossref', data
# 策略 2: arXiv ID
arxiv_id = citation_info.get('arxiv_id')
if not arxiv_id and 'note' in citation_info:
# 尝试从 note 字段提取 arXiv ID
arxiv_id = ArXivClient.extract_arxiv_id(citation_info['note'])
if arxiv_id and self.arxiv:
data = self.arxiv.search_by_id(arxiv_id)
if data:
return True, 'arxiv', data
# 策略 3: 通用搜索 (Semantic Scholar)
if 'title' in citation_info and self.semantic_scholar:
data = self.semantic_scholar.search_by_title(citation_info['title'])
if data:
return True, 'semantic_scholar', data
return False, None, None
def get_bibtex(self, doi: str) -> Optional[str]:
"""通过 DOI 获取 BibTeX
Args:
doi: DOI 标识符
Returns:
BibTeX 字符串,如果失败则返回 None
"""
if self.crossref:
return self.crossref.get_bibtex(doi)
return None
# ============================================================================
# 使用示例
# ============================================================================
if __name__ == '__main__':
# 示例 1: 使用 CrossRef 客户端
print("示例 1: CrossRef 客户端")
print("-" * 60)
crossref = CrossRefClient()
result = crossref.search_by_doi("10.48550/arXiv.1706.03762")
if result:
print(f"标题: {result['title']}")
print(f"作者: {', '.join(result['authors'][:3])}")
print(f"年份: {result['year']}")
print()
# 示例 2: 使用 arXiv 客户端
print("示例 2: arXiv 客户端")
print("-" * 60)
try:
arxiv_client = ArXivClient()
result = arxiv_client.search_by_id("1706.03762")
if result:
print(f"标题: {result['title']}")
print(f"作者: {', '.join(result['authors'][:3])}")
print(f"年份: {result['year']}")
except ImportError as e:
print(f"跳过: {e}")
print()
# 示例 3: 使用 Semantic Scholar 客户端
print("示例 3: Semantic Scholar 客户端")
print("-" * 60)
try:
ss_client = SemanticScholarClient()
result = ss_client.search_by_title("Attention is All You Need")
if result:
print(f"标题: {result['title']}")
print(f"作者: {', '.join(result['authors'][:3])}")
print(f"年份: {result['year']}")
print(f"引用数: {result['citationCount']}")
except ImportError as e:
print(f"跳过: {e}")
print()
# 示例 4: 使用统一管理器
print("示例 4: 统一 API 管理器")
print("-" * 60)
manager = CitationAPIManager()
citation_info = {
'title': 'Attention is All You Need',
'authors': ['Vaswani', 'Shazeer'],
'year': '2017'
}
exists, source, data = manager.verify_citation(citation_info)
if exists:
print(f"验证成功!")
print(f"来源: {source}")
print(f"标题: {data['title']}")
print(f"年份: {data['year']}")

View File

@@ -0,0 +1,605 @@
#!/usr/bin/env python3
"""
BibTeX and LaTeX Format Checker
独立的格式检查工具,用于验证 BibTeX 和 LaTeX 引用格式。
功能:
1. BibTeX 格式检查 - 验证条目结构、必填字段、字段格式
2. LaTeX 引用检查 - 提取引用、检查一致性
3. 快速格式验证 - 无需 API 调用的快速检查
使用方法:
python format-checker.py references.bib
python format-checker.py paper.tex --check-latex
python format-checker.py references.bib --strict
"""
import argparse
import sys
import re
from pathlib import Path
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from enum import Enum
# 尝试导入 bibtexparser
try:
import bibtexparser
from bibtexparser.bparser import BibTexParser
BIBTEX_AVAILABLE = True
except ImportError:
print("警告: bibtexparser 未安装,BibTeX 解析功能受限")
print("运行: pip install bibtexparser")
BIBTEX_AVAILABLE = False
class ErrorLevel(Enum):
"""错误级别"""
ERROR = "error" # 严重错误,必须修复
WARNING = "warning" # 警告,建议修复
INFO = "info" # 信息,可选修复
@dataclass
class FormatError:
"""格式错误数据类"""
level: ErrorLevel
location: str # 文件位置 (如 "entry:smith2020" 或 "line:42")
field: Optional[str] # 字段名 (如 "author", "year")
message: str # 错误描述
suggestion: Optional[str] = None # 修复建议
def parse_arguments():
"""解析命令行参数"""
parser = argparse.ArgumentParser(
description='检查 BibTeX 和 LaTeX 引用格式',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
%(prog)s references.bib
%(prog)s paper.tex --check-latex
%(prog)s references.bib --strict --output report.txt
%(prog)s references.bib --fix-common
"""
)
parser.add_argument(
'input_file',
type=str,
help='BibTeX 文件(.bib)或 LaTeX 文件(.tex)'
)
parser.add_argument(
'--check-latex',
action='store_true',
help='检查 LaTeX 引用(需要提供 .tex 文件)'
)
parser.add_argument(
'--strict',
action='store_true',
help='严格模式 - 将警告视为错误'
)
parser.add_argument(
'--output',
type=str,
help='输出报告文件路径'
)
parser.add_argument(
'--fix-common',
action='store_true',
help='自动修复常见格式问题'
)
parser.add_argument(
'--verbose',
action='store_true',
help='显示详细信息'
)
parser.add_argument(
'--entry-type',
type=str,
help='只检查特定类型的条目(如 article, inproceedings)'
)
return parser.parse_args()
def load_bibtex_file(file_path: str) -> List[Dict]:
"""加载 BibTeX 文件
Args:
file_path: BibTeX 文件路径
Returns:
BibTeX 条目列表
Raises:
FileNotFoundError: 文件不存在
ValueError: 文件格式错误
"""
if not BIBTEX_AVAILABLE:
raise ImportError("需要安装 bibtexparser: pip install bibtexparser")
try:
with open(file_path, 'r', encoding='utf-8') as f:
parser = BibTexParser(common_strings=True)
bib_database = bibtexparser.load(f, parser)
return bib_database.entries
except FileNotFoundError:
raise FileNotFoundError(f"文件不存在: {file_path}")
except Exception as e:
raise ValueError(f"无法解析 BibTeX 文件: {e}")
def load_latex_file(file_path: str) -> str:
"""加载 LaTeX 文件
Args:
file_path: LaTeX 文件路径
Returns:
文件内容
Raises:
FileNotFoundError: 文件不存在
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
raise FileNotFoundError(f"文件不存在: {file_path}")
except Exception as e:
raise ValueError(f"无法读取 LaTeX 文件: {e}")
# ============================================================================
# BibTeX 格式检查函数
# ============================================================================
def get_required_fields(entry_type: str) -> List[str]:
"""获取 BibTeX 条目类型的必填字段
Args:
entry_type: 条目类型 (如 'article', 'inproceedings')
Returns:
必填字段列表
"""
required_fields = {
'article': ['author', 'title', 'journal', 'year'],
'inproceedings': ['author', 'title', 'booktitle', 'year'],
'book': ['title', 'publisher', 'year'],
'incollection': ['author', 'title', 'booktitle', 'publisher', 'year'],
'inbook': ['author', 'title', 'chapter', 'publisher', 'year'],
'proceedings': ['title', 'year'],
'phdthesis': ['author', 'title', 'school', 'year'],
'mastersthesis': ['author', 'title', 'school', 'year'],
'techreport': ['author', 'title', 'institution', 'year'],
'manual': ['title'],
'misc': ['title'],
'unpublished': ['author', 'title', 'note'],
}
return required_fields.get(entry_type.lower(), ['title'])
def get_optional_fields(entry_type: str) -> List[str]:
"""获取 BibTeX 条目类型的可选字段
Args:
entry_type: 条目类型
Returns:
可选字段列表
"""
optional_fields = {
'article': ['volume', 'number', 'pages', 'month', 'doi', 'url'],
'inproceedings': ['editor', 'volume', 'series', 'pages', 'address',
'month', 'organization', 'publisher', 'doi', 'url'],
'book': ['author', 'editor', 'volume', 'series', 'address',
'edition', 'month', 'isbn', 'doi', 'url'],
}
return optional_fields.get(entry_type.lower(), [])
def check_entry_structure(entry: Dict) -> List[FormatError]:
"""检查 BibTeX 条目基本结构
Args:
entry: BibTeX 条目字典
Returns:
错误列表
"""
errors = []
# 检查条目类型
if 'ENTRYTYPE' not in entry:
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry.get('ID', 'unknown')}",
field='ENTRYTYPE',
message="缺少条目类型",
suggestion="添加条目类型,如 @article, @inproceedings"
))
return errors
# 检查 ID
if 'ID' not in entry or not entry['ID'].strip():
errors.append(FormatError(
level=ErrorLevel.ERROR,
location="entry:unknown",
field='ID',
message="缺少 citation key",
suggestion="添加唯一的 citation key"
))
# 检查必填字段
entry_type = entry.get('ENTRYTYPE', '')
required = get_required_fields(entry_type)
for field in required:
if field not in entry or not entry[field].strip():
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry.get('ID', 'unknown')}",
field=field,
message=f"缺少必填字段: {field}",
suggestion=f"添加 {field} 字段"
))
return errors
def check_field_formats(entry: Dict) -> List[FormatError]:
"""检查字段格式
Args:
entry: BibTeX 条目字典
Returns:
错误列表
"""
errors = []
entry_id = entry.get('ID', 'unknown')
# 年份格式检查
if 'year' in entry:
year = entry['year'].strip()
if not year.isdigit():
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry_id}",
field='year',
message=f"年份格式错误: {year} (应为4位数字)",
suggestion="使用4位数字年份,如 2023"
))
elif len(year) != 4:
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry_id}",
field='year',
message=f"年份格式错误: {year} (应为4位数字)",
suggestion="使用4位数字年份,如 2023"
))
else:
year_int = int(year)
if year_int < 1900 or year_int > 2030:
errors.append(FormatError(
level=ErrorLevel.WARNING,
location=f"entry:{entry_id}",
field='year',
message=f"年份超出合理范围: {year}",
suggestion="检查年份是否正确"
))
# DOI 格式检查
if 'doi' in entry:
doi = entry['doi'].strip()
if not doi.startswith('10.'):
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry_id}",
field='doi',
message=f"DOI 格式错误: {doi}",
suggestion="DOI 应以 '10.' 开头,如 10.1038/nature12345"
))
# 检查是否包含 URL 前缀
if 'doi.org' in doi or 'dx.doi.org' in doi:
errors.append(FormatError(
level=ErrorLevel.WARNING,
location=f"entry:{entry_id}",
field='doi',
message=f"DOI 包含 URL 前缀: {doi}",
suggestion="只保留 DOI 本身,移除 https://doi.org/ 前缀"
))
# 作者名格式检查
if 'author' in entry:
author = entry['author'].strip()
# 检查是否为空
if not author:
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{entry_id}",
field='author',
message="作者字段为空",
suggestion="添加作者信息"
))
# 检查格式一致性
elif ' and ' in author:
authors = author.split(' and ')
formats = []
for a in authors:
if ',' in a:
formats.append('last_first') # "Last, First"
else:
formats.append('first_last') # "First Last"
if len(set(formats)) > 1:
errors.append(FormatError(
level=ErrorLevel.WARNING,
location=f"entry:{entry_id}",
field='author',
message="作者名格式不一致",
suggestion="统一使用 'Last, First''First Last' 格式"
))
# 页码格式检查
if 'pages' in entry:
pages = entry['pages'].strip()
# 检查是否使用了正确的分隔符
if '-' in pages and '--' not in pages:
errors.append(FormatError(
level=ErrorLevel.INFO,
location=f"entry:{entry_id}",
field='pages',
message=f"页码使用单连字符: {pages}",
suggestion="建议使用双连字符 '--',如 123--145"
))
# URL 格式检查
if 'url' in entry:
url = entry['url'].strip()
if not url.startswith(('http://', 'https://')):
errors.append(FormatError(
level=ErrorLevel.WARNING,
location=f"entry:{entry_id}",
field='url',
message=f"URL 缺少协议前缀: {url}",
suggestion="添加 http:// 或 https:// 前缀"
))
return errors
def check_consistency(entries: List[Dict]) -> List[FormatError]:
"""检查条目间的一致性
Args:
entries: BibTeX 条目列表
Returns:
错误列表
"""
errors = []
# 检查重复的 citation key
ids = [e.get('ID', '') for e in entries]
duplicates = [id for id in ids if ids.count(id) > 1]
if duplicates:
for dup_id in set(duplicates):
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"entry:{dup_id}",
field='ID',
message=f"重复的 citation key: {dup_id}",
suggestion="使用唯一的 citation key"
))
# 检查作者名格式一致性
author_formats = {}
for entry in entries:
if 'author' in entry and ' and ' in entry['author']:
entry_id = entry.get('ID', 'unknown')
authors = entry['author'].split(' and ')
for author in authors:
if ',' in author:
author_formats[entry_id] = 'last_first'
else:
author_formats[entry_id] = 'first_last'
break
if len(set(author_formats.values())) > 1:
errors.append(FormatError(
level=ErrorLevel.WARNING,
location="global",
field='author',
message="不同条目使用了不同的作者名格式",
suggestion="统一使用 'Last, First''First Last' 格式"
))
return errors
# ============================================================================
# LaTeX 引用检查函数
# ============================================================================
def extract_latex_citations(tex_content: str) -> List[str]:
"""从 LaTeX 文件中提取引用
Args:
tex_content: LaTeX 文件内容
Returns:
引用 key 列表
"""
# 匹配 \cite{...} 命令
cite_pattern = r'\\cite(?:\[[^\]]*\])?(?:\[[^\]]*\])?\{([^}]+)\}'
citations = re.findall(cite_pattern, tex_content)
# 展开多个引用
all_keys = []
for cite in citations:
keys = [k.strip() for k in cite.split(',')]
all_keys.extend(keys)
return list(set(all_keys)) # 去重
def check_latex_consistency(tex_keys: List[str], bib_keys: List[str]) -> List[FormatError]:
"""检查 LaTeX 引用与 BibTeX 的一致性
Args:
tex_keys: LaTeX 中的引用 key 列表
bib_keys: BibTeX 中的 key 列表
Returns:
错误列表
"""
errors = []
tex_set = set(tex_keys)
bib_set = set(bib_keys)
# 未定义的引用
undefined = tex_set - bib_set
if undefined:
for key in sorted(undefined):
errors.append(FormatError(
level=ErrorLevel.ERROR,
location=f"latex:cite",
field=key,
message=f"未定义的引用: {key}",
suggestion=f"在 BibTeX 文件中添加 {key} 条目"
))
# 未使用的引用
unused = bib_set - tex_set
if unused:
for key in sorted(unused):
errors.append(FormatError(
level=ErrorLevel.WARNING,
location=f"bibtex:entry",
field=key,
message=f"未使用的引用: {key}",
suggestion=f"在 LaTeX 文件中引用 {key} 或从 BibTeX 中删除"
))
return errors
# ============================================================================
# 报告生成函数
# ============================================================================
def print_errors(errors: List[FormatError], verbose: bool = False):
"""打印错误列表
Args:
errors: 错误列表
verbose: 是否显示详细信息
"""
if not errors:
print("✅ 未发现格式错误")
return
# 按级别分组
errors_by_level = {
ErrorLevel.ERROR: [],
ErrorLevel.WARNING: [],
ErrorLevel.INFO: []
}
for error in errors:
errors_by_level[error.level].append(error)
# 打印统计
print("\n" + "="*60)
print("格式检查结果")
print("="*60)
print(f"❌ 错误: {len(errors_by_level[ErrorLevel.ERROR])}")
print(f"⚠️ 警告: {len(errors_by_level[ErrorLevel.WARNING])}")
print(f" 信息: {len(errors_by_level[ErrorLevel.INFO])}")
print("="*60)
# 打印详细错误
for level in [ErrorLevel.ERROR, ErrorLevel.WARNING, ErrorLevel.INFO]:
level_errors = errors_by_level[level]
if not level_errors:
continue
level_symbol = {
ErrorLevel.ERROR: "",
ErrorLevel.WARNING: "⚠️",
ErrorLevel.INFO: ""
}[level]
print(f"\n{level_symbol} {level.value.upper()} ({len(level_errors)}):\n")
for error in level_errors:
print(f" [{error.location}]", end="")
if error.field:
print(f" {error.field}:", end="")
print(f" {error.message}")
if verbose and error.suggestion:
print(f" 💡 建议: {error.suggestion}")
print()
def generate_report(errors: List[FormatError], output_file: str):
"""生成文本格式的检查报告
Args:
errors: 错误列表
output_file: 输出文件路径
"""
# 按级别分组
errors_by_level = {
ErrorLevel.ERROR: [],
ErrorLevel.WARNING: [],
ErrorLevel.INFO: []
}
for error in errors:
errors_by_level[error.level].append(error)
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# BibTeX/LaTeX 格式检查报告\n\n")
# 总体统计
f.write("## 总体统计\n\n")
f.write(f"- **错误**: {len(errors_by_level[ErrorLevel.ERROR])}\n")
f.write(f"- **警告**: {len(errors_by_level[ErrorLevel.WARNING])}\n")
f.write(f"- **信息**: {len(errors_by_level[ErrorLevel.INFO])}\n\n")
# 详细错误
for level in [ErrorLevel.ERROR, ErrorLevel.WARNING, ErrorLevel.INFO]:
level_errors = errors_by_level[level]
if not level_errors:
continue
level_name = {
ErrorLevel.ERROR: "错误",
ErrorLevel.WARNING: "警告",
ErrorLevel.INFO: "信息"
}[level]
f.write(f"## {level_name} ({len(level_errors)})\n\n")
for error in level_errors:
f.write(f"### [{error.location}]")
if error.field:
f.write(f" {error.field}")
f.write("\n\n")
f.write(f"**问题**: {error.message}\n\n")
if error.suggestion:
f.write(f"**建议**: {error.suggestion}\n\n")
print(f"\n报告已保存到: {output_file}")

View File

@@ -0,0 +1,678 @@
#!/usr/bin/env python3
"""
Citation Verification Script
四层验证机制:
1. Format Validation - BibTeX 格式检查
2. Existence Verification - API 验证论文存在性
3. Information Matching - 信息匹配(标题、作者、年份)
4. Content Validation - 综合评分和判定
使用方法:
python verify-citations.py references.bib
python verify-citations.py paper.tex --check-latex
python verify-citations.py references.bib --verbose --output report.md
"""
import argparse
import sys
import json
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass, asdict
import re
from difflib import SequenceMatcher
# 尝试导入 bibtexparser
try:
import bibtexparser
from bibtexparser.bparser import BibTexParser
except ImportError:
print("错误: 需要安装 bibtexparser")
print("运行: pip install bibtexparser")
sys.exit(1)
# 尝试导入 API 客户端库
try:
from semanticscholar import SemanticScholar
except ImportError:
print("警告: semanticscholar 未安装,将跳过 Semantic Scholar 验证")
print("运行: pip install semanticscholar")
try:
import arxiv
except ImportError:
print("警告: arxiv 未安装,将跳过 arXiv 验证")
print("运行: pip install arxiv")
try:
import requests
except ImportError:
print("错误: 需要安装 requests")
print("运行: pip install requests")
sys.exit(1)
@dataclass
class VerificationResult:
"""验证结果数据类"""
citation_key: str
status: str # verified, partial_match, low_match, failed, not_found
confidence: str # high_confidence, medium_confidence, low_confidence, no_confidence
match_score: float
format_errors: List[str]
api_source: Optional[str] # crossref, arxiv, semantic_scholar
message: str
def parse_arguments():
"""解析命令行参数"""
parser = argparse.ArgumentParser(
description='验证 BibTeX 引用的准确性和完整性',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
%(prog)s references.bib
%(prog)s paper.tex --check-latex
%(prog)s references.bib --verbose --output report.md
%(prog)s references.bib --api-only
"""
)
parser.add_argument(
'input_file',
type=str,
help='BibTeX 文件(.bib)或 LaTeX 文件(.tex)'
)
parser.add_argument(
'--check-latex',
action='store_true',
help='检查 LaTeX 引用一致性(需要提供 .tex 文件)'
)
parser.add_argument(
'--verbose',
action='store_true',
help='显示详细验证信息'
)
parser.add_argument(
'--output',
type=str,
help='输出报告文件路径(Markdown 格式)'
)
parser.add_argument(
'--api-only',
action='store_true',
help='仅进行 API 验证,跳过格式检查'
)
parser.add_argument(
'--format-only',
action='store_true',
help='仅进行格式检查,跳过 API 验证'
)
parser.add_argument(
'--threshold',
type=float,
default=0.85,
help='匹配阈值(0.0-1.0),默认 0.85'
)
return parser.parse_args()
def load_bibtex(file_path: str) -> List[Dict]:
"""加载 BibTeX 文件"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
parser = BibTexParser(common_strings=True)
bib_database = bibtexparser.load(f, parser)
return bib_database.entries
except FileNotFoundError:
print(f"错误: 文件不存在: {file_path}")
sys.exit(1)
except Exception as e:
print(f"错误: 无法解析 BibTeX 文件: {e}")
sys.exit(1)
def extract_latex_citations(tex_file: str) -> List[str]:
"""从 LaTeX 文件中提取引用"""
try:
with open(tex_file, 'r', encoding='utf-8') as f:
content = f.read()
# 匹配 \cite{...} 命令
cite_pattern = r'\\cite(?:\[[^\]]*\])?\{([^}]+)\}'
citations = re.findall(cite_pattern, content)
# 展开多个引用
all_keys = []
for cite in citations:
keys = [k.strip() for k in cite.split(',')]
all_keys.extend(keys)
return list(set(all_keys)) # 去重
except FileNotFoundError:
print(f"错误: 文件不存在: {tex_file}")
sys.exit(1)
except Exception as e:
print(f"错误: 无法解析 LaTeX 文件: {e}")
sys.exit(1)
# ============================================================================
# Layer 1: Format Validation (格式验证)
# ============================================================================
def get_required_fields(entry_type: str) -> List[str]:
"""获取 BibTeX 条目类型的必填字段"""
required_fields = {
'article': ['author', 'title', 'journal', 'year'],
'inproceedings': ['author', 'title', 'booktitle', 'year'],
'book': ['title', 'publisher', 'year'],
'misc': ['title'],
'phdthesis': ['author', 'title', 'school', 'year'],
'mastersthesis': ['author', 'title', 'school', 'year'],
'techreport': ['author', 'title', 'institution', 'year'],
}
return required_fields.get(entry_type.lower(), ['title'])
def check_bibtex_format(entry: Dict) -> List[str]:
"""检查 BibTeX 条目格式
Returns:
错误列表
"""
errors = []
# 检查条目类型
if 'ENTRYTYPE' not in entry:
errors.append("缺少条目类型")
return errors
# 检查 ID
if 'ID' not in entry:
errors.append("缺少 citation key")
# 检查必填字段
entry_type = entry.get('ENTRYTYPE', '')
required = get_required_fields(entry_type)
for field in required:
if field not in entry or not entry[field].strip():
errors.append(f"缺少必填字段: {field}")
# 年份格式检查
if 'year' in entry:
year = entry['year'].strip()
if not year.isdigit() or len(year) != 4:
errors.append(f"年份格式错误: {year}")
else:
year_int = int(year)
if year_int < 1900 or year_int > 2030:
errors.append(f"年份超出合理范围: {year}")
# DOI 格式检查
if 'doi' in entry:
doi = entry['doi'].strip()
if not doi.startswith('10.'):
errors.append(f"DOI 格式错误: {doi}")
return errors
def check_citation_consistency(tex_keys: List[str], bib_keys: List[str]) -> Dict:
"""检查 LaTeX 引用与 BibTeX 的一致性
Returns:
{'undefined': [...], 'unused': [...]}
"""
tex_set = set(tex_keys)
bib_set = set(bib_keys)
return {
'undefined': list(tex_set - bib_set),
'unused': list(bib_set - tex_set)
}
# ============================================================================
# Layer 2: Existence Verification (存在性验证)
# ============================================================================
def verify_with_crossref(doi: str) -> Optional[Dict]:
"""通过 CrossRef API 验证 DOI"""
try:
url = f"https://api.crossref.org/works/{doi}"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
return data.get('message')
return None
except Exception as e:
print(f"CrossRef API 错误: {e}")
return None
def verify_with_arxiv(arxiv_id: str) -> Optional[Dict]:
"""通过 arXiv API 验证"""
try:
search = arxiv.Search(id_list=[arxiv_id])
paper = next(search.results())
return {
'title': paper.title,
'authors': [a.name for a in paper.authors],
'year': paper.published.year,
'arxiv_id': arxiv_id
}
except Exception as e:
print(f"arXiv API 错误: {e}")
return None
def verify_with_semantic_scholar(title: str, authors: Optional[List[str]] = None) -> Optional[Dict]:
"""通过 Semantic Scholar API 验证"""
try:
sch = SemanticScholar()
results = sch.search_paper(title, limit=5)
if not results:
return None
# 返回第一个结果
paper = results[0]
return {
'title': paper.title,
'authors': [a.name for a in paper.authors] if paper.authors else [],
'year': paper.year,
'paperId': paper.paperId
}
except Exception as e:
print(f"Semantic Scholar API 错误: {e}")
return None
def verify_existence(entry: Dict) -> Tuple[bool, Optional[str], Optional[Dict]]:
"""验证论文存在性
Returns:
(exists, api_source, api_data)
"""
# 策略 1: DOI 优先
if 'doi' in entry:
data = verify_with_crossref(entry['doi'])
if data:
return True, 'crossref', data
# 策略 2: arXiv ID
if 'eprint' in entry or 'arxiv' in entry.get('note', '').lower():
arxiv_id = entry.get('eprint', '')
if not arxiv_id:
# 尝试从 note 中提取
match = re.search(r'arXiv:(\d{4}\.\d{4,5})', entry.get('note', ''))
if match:
arxiv_id = match.group(1)
if arxiv_id:
data = verify_with_arxiv(arxiv_id)
if data:
return True, 'arxiv', data
# 策略 3: 通用搜索
if 'title' in entry:
authors = entry.get('author', '').split(' and ') if 'author' in entry else None
data = verify_with_semantic_scholar(entry['title'], authors)
if data:
return True, 'semantic_scholar', data
return False, None, None
# ============================================================================
# Layer 3 & 4: Information Matching & Content Validation (信息匹配和内容验证)
# ============================================================================
def normalize_text(text: str) -> str:
"""标准化文本用于匹配"""
text = text.lower()
text = re.sub(r'[^\w\s]', '', text)
return ' '.join(text.split())
def match_title(title1: str, title2: str, threshold: float = 0.85) -> Dict:
"""标题匹配"""
t1 = normalize_text(title1)
t2 = normalize_text(title2)
ratio = SequenceMatcher(None, t1, t2).ratio()
return {
'match': ratio >= threshold,
'similarity': ratio
}
def normalize_author_name(name: str) -> str:
"""标准化作者名"""
parts = name.replace(',', '').split()
return ' '.join(sorted(parts)).lower()
def match_authors(authors1: List[str], authors2: List[str], threshold: float = 0.7) -> Dict:
"""作者匹配"""
names1 = [normalize_author_name(a) for a in authors1]
names2 = [normalize_author_name(a) for a in authors2]
set1 = set(names1)
set2 = set(names2)
intersection = len(set1 & set2)
union = len(set1 | set2)
if union == 0:
return {'match': False, 'similarity': 0}
ratio = intersection / union
return {
'match': ratio >= threshold,
'similarity': ratio
}
def match_year(year1: str, year2: int, tolerance: int = 1) -> Dict:
"""年份匹配"""
try:
y1 = int(year1)
y2 = int(year2)
diff = abs(y1 - y2)
return {
'match': diff <= tolerance,
'difference': diff
}
except (ValueError, TypeError):
return {'match': False, 'difference': None}
def calculate_match_score(entry: Dict, api_data: Dict, threshold: float) -> float:
"""计算综合匹配分数"""
scores = {}
weights = {
'title': 0.4,
'authors': 0.3,
'year': 0.2,
'venue': 0.1
}
# 标题匹配
if 'title' in entry and 'title' in api_data:
result = match_title(entry['title'], api_data['title'], threshold)
scores['title'] = result['similarity']
# 作者匹配
if 'author' in entry and 'authors' in api_data:
entry_authors = entry['author'].split(' and ')
result = match_authors(entry_authors, api_data['authors'])
scores['authors'] = result['similarity']
# 年份匹配
if 'year' in entry and 'year' in api_data:
result = match_year(entry['year'], api_data['year'])
scores['year'] = 1.0 if result['match'] else 0.0
# 计算加权总分
total_score = 0
total_weight = 0
for key, weight in weights.items():
if key in scores:
total_score += scores[key] * weight
total_weight += weight
if total_weight == 0:
return 0
return total_score / total_weight
def judge_verification_result(match_score: float) -> Dict:
"""判定验证结果"""
if match_score >= 0.9:
return {
'status': 'verified',
'level': 'high_confidence',
'message': '✅ 验证通过 - 信息完全匹配'
}
elif match_score >= 0.7:
return {
'status': 'partial_match',
'level': 'medium_confidence',
'message': '⚠️ 部分匹配 - 信息有轻微差异,建议人工确认'
}
elif match_score >= 0.5:
return {
'status': 'low_match',
'level': 'low_confidence',
'message': '❌ 匹配度低 - 信息差异较大,需要人工验证'
}
else:
return {
'status': 'failed',
'level': 'no_confidence',
'message': '❌ 验证失败 - 信息严重不匹配或论文不存在'
}
def verify_citation(entry: Dict, args) -> VerificationResult:
"""完整的引用验证流程"""
citation_key = entry.get('ID', 'unknown')
# Layer 1: 格式验证
format_errors = []
if not args.api_only:
format_errors = check_bibtex_format(entry)
# Layer 2: 存在性验证
if args.format_only:
return VerificationResult(
citation_key=citation_key,
status='format_checked',
confidence='n/a',
match_score=0.0,
format_errors=format_errors,
api_source=None,
message='仅格式检查'
)
exists, api_source, api_data = verify_existence(entry)
if not exists:
return VerificationResult(
citation_key=citation_key,
status='not_found',
confidence='no_confidence',
match_score=0.0,
format_errors=format_errors,
api_source=None,
message='❌ 论文不存在 - 无法通过任何 API 验证'
)
# Layer 3 & 4: 信息匹配和内容验证
match_score = calculate_match_score(entry, api_data, args.threshold)
judgment = judge_verification_result(match_score)
return VerificationResult(
citation_key=citation_key,
status=judgment['status'],
confidence=judgment['level'],
match_score=match_score,
format_errors=format_errors,
api_source=api_source,
message=judgment['message']
)
# ============================================================================
# Report Generation (报告生成)
# ============================================================================
def print_summary(results: List[VerificationResult], verbose: bool = False):
"""打印验证摘要"""
total = len(results)
verified = sum(1 for r in results if r.status == 'verified')
partial = sum(1 for r in results if r.status == 'partial_match')
low = sum(1 for r in results if r.status == 'low_match')
failed = sum(1 for r in results if r.status in ['failed', 'not_found'])
print("\n" + "="*60)
print("验证摘要")
print("="*60)
print(f"总引用数: {total}")
print(f"✅ 验证通过: {verified} ({verified/total*100:.1f}%)")
print(f"⚠️ 部分匹配: {partial} ({partial/total*100:.1f}%)")
print(f"❌ 匹配度低: {low} ({low/total*100:.1f}%)")
print(f"❌ 验证失败: {failed} ({failed/total*100:.1f}%)")
print("="*60)
if verbose:
print("\n详细结果:\n")
for result in results:
print(f"[{result.citation_key}]")
print(f" 状态: {result.message}")
print(f" 匹配分数: {result.match_score:.2f}")
if result.api_source:
print(f" 验证源: {result.api_source}")
if result.format_errors:
print(f" 格式错误: {', '.join(result.format_errors)}")
print()
def generate_markdown_report(results: List[VerificationResult], output_file: str):
"""生成 Markdown 格式的验证报告"""
total = len(results)
verified = sum(1 for r in results if r.status == 'verified')
partial = sum(1 for r in results if r.status == 'partial_match')
low = sum(1 for r in results if r.status == 'low_match')
failed = sum(1 for r in results if r.status in ['failed', 'not_found'])
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# Citation Verification Report\n\n")
# 总体统计
f.write("## 总体统计\n\n")
f.write(f"- **总引用数**: {total}\n")
f.write(f"- **✅ 验证通过**: {verified} ({verified/total*100:.1f}%)\n")
f.write(f"- **⚠️ 部分匹配**: {partial} ({partial/total*100:.1f}%)\n")
f.write(f"- **❌ 匹配度低**: {low} ({low/total*100:.1f}%)\n")
f.write(f"- **❌ 验证失败**: {failed} ({failed/total*100:.1f}%)\n\n")
# 详细结果
f.write("## 详细结果\n\n")
# 按状态分组
for status, emoji, title in [
('verified', '', '验证通过'),
('partial_match', '⚠️', '部分匹配'),
('low_match', '', '匹配度低'),
('failed', '', '验证失败'),
('not_found', '', '论文不存在')
]:
status_results = [r for r in results if r.status == status]
if status_results:
f.write(f"### {emoji} {title} ({len(status_results)})\n\n")
for result in status_results:
f.write(f"#### `{result.citation_key}`\n\n")
f.write(f"- **状态**: {result.message}\n")
f.write(f"- **匹配分数**: {result.match_score:.2f}\n")
f.write(f"- **置信度**: {result.confidence}\n")
if result.api_source:
f.write(f"- **验证源**: {result.api_source}\n")
if result.format_errors:
f.write(f"- **格式错误**:\n")
for error in result.format_errors:
f.write(f" - {error}\n")
f.write("\n")
# 建议操作
f.write("## 建议操作\n\n")
if failed > 0:
f.write("### 需要修正的引用\n\n")
failed_results = [r for r in results if r.status in ['failed', 'not_found']]
for result in failed_results:
f.write(f"- `{result.citation_key}`: {result.message}\n")
f.write("\n")
if partial > 0 or low > 0:
f.write("### 需要人工确认的引用\n\n")
check_results = [r for r in results if r.status in ['partial_match', 'low_match']]
for result in check_results:
f.write(f"- `{result.citation_key}`: {result.message}\n")
f.write("\n")
print(f"\n报告已保存到: {output_file}")
# ============================================================================
# Main Function (主函数)
# ============================================================================
def main():
"""主函数"""
args = parse_arguments()
# 加载 BibTeX 文件
print(f"正在加载 BibTeX 文件: {args.input_file}")
entries = load_bibtex(args.input_file)
print(f"找到 {len(entries)} 个引用条目")
# LaTeX 一致性检查
if args.check_latex:
tex_file = args.input_file.replace('.bib', '.tex')
if Path(tex_file).exists():
print(f"\n正在检查 LaTeX 引用一致性: {tex_file}")
tex_keys = extract_latex_citations(tex_file)
bib_keys = [e['ID'] for e in entries]
consistency = check_citation_consistency(tex_keys, bib_keys)
if consistency['undefined']:
print(f"⚠️ 未定义的引用 ({len(consistency['undefined'])}): {', '.join(consistency['undefined'])}")
if consistency['unused']:
print(f"⚠️ 未使用的引用 ({len(consistency['unused'])}): {', '.join(consistency['unused'])}")
if not consistency['undefined'] and not consistency['unused']:
print("✅ LaTeX 引用与 BibTeX 完全一致")
# 验证每个引用
print("\n开始验证引用...")
results = []
for i, entry in enumerate(entries, 1):
citation_key = entry.get('ID', 'unknown')
print(f"[{i}/{len(entries)}] 验证 {citation_key}...", end=' ')
result = verify_citation(entry, args)
results.append(result)
# 简短状态输出
if result.status == 'verified':
print("")
elif result.status == 'partial_match':
print("⚠️")
else:
print("")
# 打印摘要
print_summary(results, args.verbose)
# 生成报告
if args.output:
generate_markdown_report(results, args.output)
# 返回退出码
failed_count = sum(1 for r in results if r.status in ['failed', 'not_found'])
return 0 if failed_count == 0 else 1
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,521 @@
---
name: code-review-excellence
description: This skill should be used when the user asks to review a diff or pull request, write review comments, audit code quality, establish review standards, or improve how a team performs code review.
version: 0.1.0
---
# Code Review Excellence
Transform code reviews from gatekeeping to knowledge sharing through constructive feedback, systematic analysis, and collaborative improvement.
## When to Use This Skill
- Reviewing pull requests and code changes
- Establishing code review standards for teams
- Mentoring junior developers through reviews
- Conducting architecture reviews
- Creating review checklists and guidelines
- Improving team collaboration
- Reducing code review cycle time
- Maintaining code quality standards
## Core Principles
### 1. The Review Mindset
**Goals of Code Review:**
- Catch bugs and edge cases
- Ensure code maintainability
- Share knowledge across team
- Enforce coding standards
- Improve design and architecture
- Build team culture
**Not the Goals:**
- Show off knowledge
- Nitpick formatting (use linters)
- Block progress unnecessarily
- Rewrite to your preference
### 2. Effective Feedback
**Good Feedback is:**
- Specific and actionable
- Educational, not judgmental
- Focused on the code, not the person
- Balanced (praise good work too)
- Prioritized (critical vs nice-to-have)
```markdown
❌ Bad: "This is wrong."
✅ Good: "This could cause a race condition when multiple users
access simultaneously. Consider using a mutex here."
❌ Bad: "Why didn't you use X pattern?"
✅ Good: "Have you considered the Repository pattern? It would
make this easier to test. Here's an example: [link]"
❌ Bad: "Rename this variable."
✅ Good: "[nit] Consider `userCount` instead of `uc` for
clarity. Not blocking if you prefer to keep it."
```
### 3. Review Scope
**What to Review:**
- Logic correctness and edge cases
- Security vulnerabilities
- Performance implications
- Test coverage and quality
- Error handling
- Documentation and comments
- API design and naming
- Architectural fit
**What Not to Review Manually:**
- Code formatting (use Prettier, Black, etc.)
- Import organization
- Linting violations
- Simple typos
## Review Process
### Phase 1: Context Gathering (2-3 minutes)
```markdown
Before diving into code, understand:
1. Read PR description and linked issue
2. Check PR size (>400 lines? Ask to split)
3. Review CI/CD status (tests passing?)
4. Understand the business requirement
5. Note any relevant architectural decisions
```
### Phase 2: High-Level Review (5-10 minutes)
```markdown
1. **Architecture & Design**
- Does the solution fit the problem?
- Are there simpler approaches?
- Is it consistent with existing patterns?
- Will it scale?
2. **File Organization**
- Are new files in the right places?
- Is code grouped logically?
- Are there duplicate files?
3. **Testing Strategy**
- Are there tests?
- Do tests cover edge cases?
- Are tests readable?
```
### Phase 3: Line-by-Line Review (10-20 minutes)
```markdown
For each file:
1. **Logic & Correctness**
- Edge cases handled?
- Off-by-one errors?
- Null/undefined checks?
- Race conditions?
2. **Security**
- Input validation?
- SQL injection risks?
- XSS vulnerabilities?
- Sensitive data exposure?
3. **Performance**
- N+1 queries?
- Unnecessary loops?
- Memory leaks?
- Blocking operations?
4. **Maintainability**
- Clear variable names?
- Functions doing one thing?
- Complex code commented?
- Magic numbers extracted?
```
### Phase 4: Summary & Decision (2-3 minutes)
```markdown
1. Summarize key concerns
2. Highlight what you liked
3. Make clear decision:
- ✅ Approve
- 💬 Comment (minor suggestions)
- 🔄 Request Changes (must address)
4. Offer to pair if complex
```
## Review Techniques
### Technique 1: The Checklist Method
```markdown
## Security Checklist
- [ ] User input validated and sanitized
- [ ] SQL queries use parameterization
- [ ] Authentication/authorization checked
- [ ] Secrets not hardcoded
- [ ] Error messages don't leak info
## Performance Checklist
- [ ] No N+1 queries
- [ ] Database queries indexed
- [ ] Large lists paginated
- [ ] Expensive operations cached
- [ ] No blocking I/O in hot paths
## Testing Checklist
- [ ] Happy path tested
- [ ] Edge cases covered
- [ ] Error cases tested
- [ ] Test names are descriptive
- [ ] Tests are deterministic
```
### Technique 2: The Question Approach
Instead of stating problems, ask questions to encourage thinking:
```markdown
❌ "This will fail if the list is empty."
✅ "What happens if `items` is an empty array?"
❌ "You need error handling here."
✅ "How should this behave if the API call fails?"
❌ "This is inefficient."
✅ "I see this loops through all users. Have we considered
the performance impact with 100k users?"
```
### Technique 3: Suggest, Don't Command
```markdown
## Use Collaborative Language
❌ "You must change this to use async/await"
✅ "Suggestion: async/await might make this more readable:
```typescript
async function fetchUser(id: string) {
const user = await db.query('SELECT * FROM users WHERE id = ?', id);
return user;
}
```
What do you think?"
❌ "Extract this into a function"
✅ "This logic appears in 3 places. Would it make sense to
extract it into a shared utility function?"
```
### Technique 4: Differentiate Severity
```markdown
Use labels to indicate priority:
🔴 [blocking] - Must fix before merge
🟡 [important] - Should fix, discuss if disagree
🟢 [nit] - Nice to have, not blocking
💡 [suggestion] - Alternative approach to consider
📚 [learning] - Educational comment, no action needed
🎉 [praise] - Good work, keep it up!
Example:
"🔴 [blocking] This SQL query is vulnerable to injection.
Please use parameterized queries."
"🟢 [nit] Consider renaming `data` to `userData` for clarity."
"🎉 [praise] Excellent test coverage! This will catch edge cases."
```
## Language-Specific Patterns
### Python Code Review
```python
# Check for Python-specific issues
# ❌ Mutable default arguments
def add_item(item, items=[]): # Bug! Shared across calls
items.append(item)
return items
# ✅ Use None as default
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
# ❌ Catching too broad
try:
result = risky_operation()
except: # Catches everything, even KeyboardInterrupt!
pass
# ✅ Catch specific exceptions
try:
result = risky_operation()
except ValueError as e:
logger.error(f"Invalid value: {e}")
raise
# ❌ Using mutable class attributes
class User:
permissions = [] # Shared across all instances!
# ✅ Initialize in __init__
class User:
def __init__(self):
self.permissions = []
```
### TypeScript/JavaScript Code Review
```typescript
// Check for TypeScript-specific issues
// ❌ Using any defeats type safety
function processData(data: any) { // Avoid any
return data.value;
}
// ✅ Use proper types
interface DataPayload {
value: string;
}
function processData(data: DataPayload) {
return data.value;
}
// ❌ Not handling async errors
async function fetchUser(id: string) {
const response = await fetch(`/api/users/${id}`);
return response.json(); // What if network fails?
}
// ✅ Handle errors properly
async function fetchUser(id: string): Promise<User> {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Failed to fetch user:', error);
throw error;
}
}
// ❌ Mutation of props
function UserProfile({ user }: Props) {
user.lastViewed = new Date(); // Mutating prop!
return <div>{user.name}</div>;
}
// ✅ Don't mutate props
function UserProfile({ user, onView }: Props) {
useEffect(() => {
onView(user.id); // Notify parent to update
}, [user.id]);
return <div>{user.name}</div>;
}
```
## Advanced Review Patterns
### Pattern 1: Architectural Review
```markdown
When reviewing significant changes:
1. **Design Document First**
- For large features, request design doc before code
- Review design with team before implementation
- Agree on approach to avoid rework
2. **Review in Stages**
- First PR: Core abstractions and interfaces
- Second PR: Implementation
- Third PR: Integration and tests
- Easier to review, faster to iterate
3. **Consider Alternatives**
- "Have we considered using [pattern/library]?"
- "What's the tradeoff vs. the simpler approach?"
- "How will this evolve as requirements change?"
```
### Pattern 2: Test Quality Review
```typescript
// ❌ Poor test: Implementation detail testing
test('increments counter variable', () => {
const component = render(<Counter />);
const button = component.getByRole('button');
fireEvent.click(button);
expect(component.state.counter).toBe(1); // Testing internal state
});
// ✅ Good test: Behavior testing
test('displays incremented count when clicked', () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
// Review questions for tests:
// - Do tests describe behavior, not implementation?
// - Are test names clear and descriptive?
// - Do tests cover edge cases?
// - Are tests independent (no shared state)?
// - Can tests run in any order?
```
### Pattern 3: Security Review
```markdown
## Security Review Checklist
### Authentication & Authorization
- [ ] Is authentication required where needed?
- [ ] Are authorization checks before every action?
- [ ] Is JWT validation proper (signature, expiry)?
- [ ] Are API keys/secrets properly secured?
### Input Validation
- [ ] All user inputs validated?
- [ ] File uploads restricted (size, type)?
- [ ] SQL queries parameterized?
- [ ] XSS protection (escape output)?
### Data Protection
- [ ] Passwords hashed (bcrypt/argon2)?
- [ ] Sensitive data encrypted at rest?
- [ ] HTTPS enforced for sensitive data?
- [ ] PII handled according to regulations?
### Common Vulnerabilities
- [ ] No eval() or similar dynamic execution?
- [ ] No hardcoded secrets?
- [ ] CSRF protection for state-changing operations?
- [ ] Rate limiting on public endpoints?
```
## Giving Difficult Feedback
### Pattern: The Sandwich Method (Modified)
```markdown
Traditional: Praise + Criticism + Praise (feels fake)
Better: Context + Specific Issue + Helpful Solution
Example:
"I noticed the payment processing logic is inline in the
controller. This makes it harder to test and reuse.
[Specific Issue]
The calculateTotal() function mixes tax calculation,
discount logic, and database queries, making it difficult
to unit test and reason about.
[Helpful Solution]
Could we extract this into a PaymentService class? That
would make it testable and reusable. I can pair with you
on this if helpful."
```
### Handling Disagreements
```markdown
When author disagrees with your feedback:
1. **Seek to Understand**
"Help me understand your approach. What led you to
choose this pattern?"
2. **Acknowledge Valid Points**
"That's a good point about X. I hadn't considered that."
3. **Provide Data**
"I'm concerned about performance. Can we add a benchmark
to validate the approach?"
4. **Escalate if Needed**
"Let's get [architect/senior dev] to weigh in on this."
5. **Know When to Let Go**
If it's working and not a critical issue, approve it.
Perfection is the enemy of progress.
```
## Best Practices
1. **Review Promptly**: Within 24 hours, ideally same day
2. **Limit PR Size**: 200-400 lines max for effective review
3. **Review in Time Blocks**: 60 minutes max, take breaks
4. **Use Review Tools**: GitHub, GitLab, or dedicated tools
5. **Automate What You Can**: Linters, formatters, security scans
6. **Build Rapport**: Emoji, praise, and empathy matter
7. **Be Available**: Offer to pair on complex issues
8. **Learn from Others**: Review others' review comments
## Common Pitfalls
- **Perfectionism**: Blocking PRs for minor style preferences
- **Scope Creep**: "While you're at it, can you also..."
- **Inconsistency**: Different standards for different people
- **Delayed Reviews**: Letting PRs sit for days
- **Ghosting**: Requesting changes then disappearing
- **Rubber Stamping**: Approving without actually reviewing
- **Bike Shedding**: Debating trivial details extensively
## Templates
### PR Review Comment Template
```markdown
## Summary
[Brief overview of what was reviewed]
## Strengths
- [What was done well]
- [Good patterns or approaches]
## Required Changes
🔴 [Blocking issue 1]
🔴 [Blocking issue 2]
## Suggestions
💡 [Improvement 1]
💡 [Improvement 2]
## Questions
❓ [Clarification needed on X]
❓ [Alternative approach consideration]
## Verdict
✅ Approve after addressing required changes
```
## Resources
- **references/code-review-best-practices.md**: Comprehensive review guidelines
- **references/common-bugs-checklist.md**: Language-specific bugs to watch for
- **references/security-review-guide.md**: Security-focused review checklist
- **assets/pr-review-template.md**: Standard review comment template
- **assets/review-checklist.md**: Quick reference checklist
- **scripts/pr-analyzer.py**: Analyze PR complexity and suggest reviewers

View File

@@ -0,0 +1,12 @@
## Summary
- Scope:
- Overall verdict:
## Strengths
-
## Required changes
-
## Suggestions
-

View File

@@ -0,0 +1,6 @@
- Intent understood
- Correctness checked
- Tests reviewed
- Security checked
- Performance checked
- Decision recorded

View File

@@ -0,0 +1,19 @@
# Code Review Best Practices
## Default review order
1. Understand intent and scope.
2. Check architecture and correctness.
3. Check tests and failure handling.
4. Check security and performance risks.
5. Leave clear, prioritized comments.
## Comment severity
- `blocking` - correctness, security, data loss, major maintainability issue
- `important` - should be fixed before merge if practical
- `nit` - polish only
## Good reviewer habits
- summarize first,
- separate required changes from suggestions,
- quote the code path or failure mode,
- praise good decisions when they matter.

View File

@@ -0,0 +1,9 @@
# Common Bugs Checklist
- null / undefined handling
- off-by-one and empty-input behavior
- race conditions or double-submit paths
- missing authorization checks
- silent error swallowing
- expensive loops or repeated queries
- test gaps on unhappy paths

View File

@@ -0,0 +1,12 @@
# Security Review Guide
## Check for
- unsanitized input,
- SQL or shell injection,
- insecure deserialization,
- secret leakage,
- missing authz checks,
- unsafe filesystem or network defaults.
## Review note pattern
`Blocking: this path accepts untrusted input and passes it to X without validation.`

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import subprocess
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description='Summarize git diff size for review planning.')
parser.add_argument('--repo', default='.', help='Repository path')
parser.add_argument('--base', default='HEAD~1', help='Base revision')
parser.add_argument('--head', default='HEAD', help='Head revision')
return parser.parse_args()
def main() -> int:
args = parse_args()
repo = Path(args.repo).resolve()
result = subprocess.run(
['git', '-C', str(repo), 'diff', '--numstat', args.base, args.head],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
print(result.stderr.strip() or 'git diff failed')
return result.returncode
files = 0
added = 0
deleted = 0
for line in result.stdout.splitlines():
parts = line.split(' ')
if len(parts) != 3:
continue
a, d, _ = parts
if a.isdigit():
added += int(a)
if d.isdigit():
deleted += int(d)
files += 1
print(f'files={files}')
print(f'added={added}')
print(f'deleted={deleted}')
return 0
if __name__ == '__main__':
raise SystemExit(main())

View File

@@ -0,0 +1,272 @@
# Command Development Skill
Comprehensive guidance on creating Claude Code slash commands, including file format, frontmatter options, dynamic arguments, and best practices.
## Overview
This skill provides knowledge about:
- Slash command file format and structure
- YAML frontmatter configuration fields
- Dynamic arguments ($ARGUMENTS, $1, $2, etc.)
- File references with @ syntax
- Bash execution with !` syntax
- Command organization and namespacing
- Best practices for command development
- Plugin-specific features (${CLAUDE_PLUGIN_ROOT}, plugin patterns)
- Integration with plugin components (agents, skills, hooks)
- Validation patterns and error handling
## Skill Structure
### SKILL.md (~2,470 words)
Core skill content covering:
**Fundamentals:**
- Command basics and locations
- File format (Markdown with optional frontmatter)
- YAML frontmatter fields overview
- Dynamic arguments ($ARGUMENTS and positional)
- File references (@ syntax)
- Bash execution (!` syntax)
- Command organization patterns
- Best practices and common patterns
- Troubleshooting
**Plugin-Specific:**
- ${CLAUDE_PLUGIN_ROOT} environment variable
- Plugin command discovery and organization
- Plugin command patterns (configuration, template, multi-script)
- Integration with plugin components (agents, skills, hooks)
- Validation patterns (argument, file, resource, error handling)
### References
Detailed documentation:
- **frontmatter-reference.md**: Complete YAML frontmatter field specifications
- All field descriptions with types and defaults
- When to use each field
- Examples and best practices
- Validation and common errors
- **plugin-features-reference.md**: Plugin-specific command features
- Plugin command discovery and organization
- ${CLAUDE_PLUGIN_ROOT} environment variable usage
- Plugin command patterns (configuration, template, multi-script)
- Integration with plugin agents, skills, and hooks
- Validation patterns and error handling
### Examples
Practical command examples:
- **simple-commands.md**: 10 complete command examples
- Code review commands
- Testing commands
- Deployment commands
- Documentation generators
- Git integration commands
- Analysis and research commands
- **plugin-commands.md**: 10 plugin-specific command examples
- Simple plugin commands with scripts
- Multi-script workflows
- Template-based generation
- Configuration-driven deployment
- Agent and skill integration
- Multi-component workflows
- Validated input commands
- Environment-aware commands
## When This Skill Triggers
Claude Code activates this skill when users:
- Ask to "create a slash command" or "add a command"
- Need to "write a custom command"
- Want to "define command arguments"
- Ask about "command frontmatter" or YAML configuration
- Need to "organize commands" or use namespacing
- Want to create commands with file references
- Ask about "bash execution in commands"
- Need command development best practices
## Progressive Disclosure
The skill uses progressive disclosure:
1. **SKILL.md** (~2,470 words): Core concepts, common patterns, and plugin features overview
2. **References** (~13,500 words total): Detailed specifications
- frontmatter-reference.md (~1,200 words)
- plugin-features-reference.md (~1,800 words)
- interactive-commands.md (~2,500 words)
- advanced-workflows.md (~1,700 words)
- testing-strategies.md (~2,200 words)
- documentation-patterns.md (~2,000 words)
- marketplace-considerations.md (~2,200 words)
3. **Examples** (~6,000 words total): Complete working command examples
- simple-commands.md
- plugin-commands.md
Claude loads references and examples as needed based on task.
## Command Basics Quick Reference
### File Format
```markdown
---
description: Brief description
argument-hint: [arg1] [arg2]
allowed-tools: Read, Bash(git:*)
---
Command prompt content with:
- Arguments: $1, $2, or $ARGUMENTS
- Files: @path/to/file
- Bash: !`command here`
```
### Locations
- **Project**: `.claude/commands/` (shared with team)
- **Personal**: `~/.claude/commands/` (your commands)
- **Plugin**: `plugin-name/commands/` (plugin-specific)
### Key Features
**Dynamic arguments:**
- `$ARGUMENTS` - All arguments as single string
- `$1`, `$2`, `$3` - Positional arguments
**File references:**
- `@path/to/file` - Include file contents
**Bash execution:**
- `!`command`` - Execute and include output
## Frontmatter Fields Quick Reference
| Field | Purpose | Example |
|-------|---------|---------|
| `description` | Brief description for /help | `"Review code for issues"` |
| `allowed-tools` | Restrict tool access | `Read, Bash(git:*)` |
| `model` | Specify model | `sonnet`, `opus`, `haiku` |
| `argument-hint` | Document arguments | `[pr-number] [priority]` |
| `disable-model-invocation` | Manual-only command | `true` |
## Common Patterns
### Simple Review Command
```markdown
---
description: Review code for issues
---
Review this code for quality and potential bugs.
```
### Command with Arguments
```markdown
---
description: Deploy to environment
argument-hint: [environment] [version]
---
Deploy to $1 environment using version $2
```
### Command with File Reference
```markdown
---
description: Document file
argument-hint: [file-path]
---
Generate documentation for @$1
```
### Command with Bash Execution
```markdown
---
description: Show Git status
allowed-tools: Bash(git:*)
---
Current status: !`git status`
Recent commits: !`git log --oneline -5`
```
## Development Workflow
1. **Design command:**
- Define purpose and scope
- Determine required arguments
- Identify needed tools
2. **Create file:**
- Choose appropriate location
- Create `.md` file with command name
- Write basic prompt
3. **Add frontmatter:**
- Start minimal (just description)
- Add fields as needed (allowed-tools, etc.)
- Document arguments with argument-hint
4. **Test command:**
- Invoke with `/command-name`
- Verify arguments work
- Check bash execution
- Test file references
5. **Refine:**
- Improve prompt clarity
- Handle edge cases
- Add examples in comments
- Document requirements
## Best Practices Summary
1. **Single responsibility**: One command, one clear purpose
2. **Clear descriptions**: Make discoverable in `/help`
3. **Document arguments**: Always use argument-hint
4. **Minimal tools**: Use most restrictive allowed-tools
5. **Test thoroughly**: Verify all features work
6. **Add comments**: Explain complex logic
7. **Handle errors**: Consider missing arguments/files
## Status
**Completed enhancements:**
- ✓ Plugin command patterns (${CLAUDE_PLUGIN_ROOT}, discovery, organization)
- ✓ Integration patterns (agents, skills, hooks coordination)
- ✓ Validation patterns (input, file, resource validation, error handling)
**Remaining enhancements (in progress):**
- Advanced workflows (multi-step command sequences)
- Testing strategies (how to test commands effectively)
- Documentation patterns (command documentation best practices)
- Marketplace considerations (publishing and distribution)
## Maintenance
To update this skill:
1. Keep SKILL.md focused on core fundamentals
2. Move detailed specifications to references/
3. Add new examples/ for different use cases
4. Update frontmatter when new fields added
5. Ensure imperative/infinitive form throughout
6. Test examples work with current Claude Code
## Version History
**v0.1.0** (2025-01-15):
- Initial release with basic command fundamentals
- Frontmatter field reference
- 10 simple command examples
- Ready for plugin-specific pattern additions

View File

@@ -0,0 +1,835 @@
---
name: command-development
description: This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
version: 0.2.0
---
# Command Development for Claude Code
## Overview
Slash commands are frequently-used prompts defined as Markdown files that Claude executes during interactive sessions. Understanding command structure, frontmatter options, and dynamic features enables creating powerful, reusable workflows.
**Key concepts:**
- Markdown file format for commands
- YAML frontmatter for configuration
- Dynamic arguments and file references
- Bash execution for context
- Command organization and namespacing
## Command Basics
### What is a Slash Command?
A slash command is a Markdown file containing a prompt that Claude executes when invoked. Commands provide:
- **Reusability**: Define once, use repeatedly
- **Consistency**: Standardize common workflows
- **Sharing**: Distribute across team or projects
- **Efficiency**: Quick access to complex prompts
### Critical: Commands are Instructions FOR Claude
**Commands are written for agent consumption, not human consumption.**
When a user invokes `/command-name`, the command content becomes Claude's instructions. Write commands as directives TO Claude about what to do, not as messages TO the user.
**Correct approach (instructions for Claude):**
```markdown
Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication issues
Provide specific line numbers and severity ratings.
```
**Incorrect approach (messages to user):**
```markdown
This command will review your code for security issues.
You'll receive a report with vulnerability details.
```
The first example tells Claude what to do. The second tells the user what will happen but doesn't instruct Claude. Always use the first approach.
### Command Locations
**Project commands** (shared with team):
- Location: `.claude/commands/`
- Scope: Available in specific project
- Label: Shown as "(project)" in `/help`
- Use for: Team workflows, project-specific tasks
**Personal commands** (available everywhere):
- Location: `~/.claude/commands/`
- Scope: Available in all projects
- Label: Shown as "(user)" in `/help`
- Use for: Personal workflows, cross-project utilities
**Plugin commands** (bundled with plugins):
- Location: `plugin-name/commands/`
- Scope: Available when plugin installed
- Label: Shown as "(plugin-name)" in `/help`
- Use for: Plugin-specific functionality
## File Format
### Basic Structure
Commands are Markdown files with `.md` extension:
```
.claude/commands/
├── review.md # /review command
├── test.md # /test command
└── deploy.md # /deploy command
```
**Simple command:**
```markdown
Review this code for security vulnerabilities including:
- SQL injection
- XSS attacks
- Authentication bypass
- Insecure data handling
```
No frontmatter needed for basic commands.
### With YAML Frontmatter
Add configuration using YAML frontmatter:
```markdown
---
description: Review code for security issues
allowed-tools: Read, Grep, Bash(git:*)
model: sonnet
---
Review this code for security vulnerabilities...
```
## YAML Frontmatter Fields
### description
**Purpose:** Brief description shown in `/help`
**Type:** String
**Default:** First line of command prompt
```yaml
---
description: Review pull request for code quality
---
```
**Best practice:** Clear, actionable description (under 60 characters)
### allowed-tools
**Purpose:** Specify which tools command can use
**Type:** String or Array
**Default:** Inherits from conversation
```yaml
---
allowed-tools: Read, Write, Edit, Bash(git:*)
---
```
**Patterns:**
- `Read, Write, Edit` - Specific tools
- `Bash(git:*)` - Bash with git commands only
- `*` - All tools (rarely needed)
**Use when:** Command requires specific tool access
### model
**Purpose:** Specify model for command execution
**Type:** String (sonnet, opus, haiku)
**Default:** Inherits from conversation
```yaml
---
model: haiku
---
```
**Use cases:**
- `haiku` - Fast, simple commands
- `sonnet` - Standard workflows
- `opus` - Complex analysis
### argument-hint
**Purpose:** Document expected arguments for autocomplete
**Type:** String
**Default:** None
```yaml
---
argument-hint: [pr-number] [priority] [assignee]
---
```
**Benefits:**
- Helps users understand command arguments
- Improves command discovery
- Documents command interface
### disable-model-invocation
**Purpose:** Prevent SlashCommand tool from programmatically calling command
**Type:** Boolean
**Default:** false
```yaml
---
disable-model-invocation: true
---
```
**Use when:** Command should only be manually invoked
## Dynamic Arguments
### Using $ARGUMENTS
Capture all arguments as single string:
```markdown
---
description: Fix issue by number
argument-hint: [issue-number]
---
Fix issue #$ARGUMENTS following our coding standards and best practices.
```
**Usage:**
```
> /fix-issue 123
> /fix-issue 456
```
**Expands to:**
```
Fix issue #123 following our coding standards...
Fix issue #456 following our coding standards...
```
### Using Positional Arguments
Capture individual arguments with `$1`, `$2`, `$3`, etc.:
```markdown
---
description: Review PR with priority and assignee
argument-hint: [pr-number] [priority] [assignee]
---
Review pull request #$1 with priority level $2.
After review, assign to $3 for follow-up.
```
**Usage:**
```
> /review-pr 123 high alice
```
**Expands to:**
```
Review pull request #123 with priority level high.
After review, assign to alice for follow-up.
```
### Combining Arguments
Mix positional and remaining arguments:
```markdown
Deploy $1 to $2 environment with options: $3
```
**Usage:**
```
> /deploy api staging --force --skip-tests
```
**Expands to:**
```
Deploy api to staging environment with options: --force --skip-tests
```
## File References
### Using @ Syntax
Include file contents in command:
```markdown
---
description: Review specific file
argument-hint: [file-path]
---
Review @$1 for:
- Code quality
- Best practices
- Potential bugs
```
**Usage:**
```
> /review-file src/api/users.ts
```
**Effect:** Claude reads `src/api/users.ts` before processing command
### Multiple File References
Reference multiple files:
```markdown
Compare @src/old-version.js with @src/new-version.js
Identify:
- Breaking changes
- New features
- Bug fixes
```
### Static File References
Reference known files without arguments:
```markdown
Review @package.json and @tsconfig.json for consistency
Ensure:
- TypeScript version matches
- Dependencies are aligned
- Build configuration is correct
```
## Bash Execution in Commands
Commands can execute bash commands inline to dynamically gather context before Claude processes the command. This is useful for including repository state, environment information, or project-specific context.
**When to use:**
- Include dynamic context (git status, environment vars, etc.)
- Gather project/repository state
- Build context-aware workflows
**Implementation details:**
For complete syntax, examples, and best practices, see `references/plugin-features-reference.md` section on bash execution. The reference includes the exact syntax and multiple working examples to avoid execution issues
## Command Organization
### Flat Structure
Simple organization for small command sets:
```
.claude/commands/
├── build.md
├── test.md
├── deploy.md
├── review.md
└── docs.md
```
**Use when:** 5-15 commands, no clear categories
### Namespaced Structure
Organize commands in subdirectories:
```
.claude/commands/
├── ci/
│ ├── build.md # /build (project:ci)
│ ├── test.md # /test (project:ci)
│ └── lint.md # /lint (project:ci)
├── git/
│ ├── commit.md # /commit (project:git)
│ └── pr.md # /pr (project:git)
└── docs/
├── generate.md # /generate (project:docs)
└── publish.md # /publish (project:docs)
```
**Benefits:**
- Logical grouping by category
- Namespace shown in `/help`
- Easier to find related commands
**Use when:** 15+ commands, clear categories
## Best Practices
### Command Design
1. **Single responsibility:** One command, one task
2. **Clear descriptions:** Self-explanatory in `/help`
3. **Explicit dependencies:** Use `allowed-tools` when needed
4. **Document arguments:** Always provide `argument-hint`
5. **Consistent naming:** Use verb-noun pattern (review-pr, fix-issue)
### Argument Handling
1. **Validate arguments:** Check for required arguments in prompt
2. **Provide defaults:** Suggest defaults when arguments missing
3. **Document format:** Explain expected argument format
4. **Handle edge cases:** Consider missing or invalid arguments
```markdown
---
argument-hint: [pr-number]
---
$IF($1,
Review PR #$1,
Please provide a PR number. Usage: /review-pr [number]
)
```
### File References
1. **Explicit paths:** Use clear file paths
2. **Check existence:** Handle missing files gracefully
3. **Relative paths:** Use project-relative paths
4. **Glob support:** Consider using Glob tool for patterns
### Bash Commands
1. **Limit scope:** Use `Bash(git:*)` not `Bash(*)`
2. **Safe commands:** Avoid destructive operations
3. **Handle errors:** Consider command failures
4. **Keep fast:** Long-running commands slow invocation
### Documentation
1. **Add comments:** Explain complex logic
2. **Provide examples:** Show usage in comments
3. **List requirements:** Document dependencies
4. **Version commands:** Note breaking changes
```markdown
---
description: Deploy application to environment
argument-hint: [environment] [version]
---
<!--
Usage: /deploy [staging|production] [version]
Requires: AWS credentials configured
Example: /deploy staging v1.2.3
-->
Deploy application to $1 environment using version $2...
```
## Common Patterns
### Review Pattern
```markdown
---
description: Review code changes
allowed-tools: Read, Bash(git:*)
---
Files changed: !`git diff --name-only`
Review each file for:
1. Code quality and style
2. Potential bugs or issues
3. Test coverage
4. Documentation needs
Provide specific feedback for each file.
```
### Testing Pattern
```markdown
---
description: Run tests for specific file
argument-hint: [test-file]
allowed-tools: Bash(npm:*)
---
Run tests: !`npm test $1`
Analyze results and suggest fixes for failures.
```
### Documentation Pattern
```markdown
---
description: Generate documentation for file
argument-hint: [source-file]
---
Generate comprehensive documentation for @$1 including:
- Function/class descriptions
- Parameter documentation
- Return value descriptions
- Usage examples
- Edge cases and errors
```
### Workflow Pattern
```markdown
---
description: Complete PR workflow
argument-hint: [pr-number]
allowed-tools: Bash(gh:*), Read
---
PR #$1 Workflow:
1. Fetch PR: !`gh pr view $1`
2. Review changes
3. Run checks
4. Approve or request changes
```
## Troubleshooting
**Command not appearing:**
- Check file is in correct directory
- Verify `.md` extension present
- Ensure valid Markdown format
- Restart Claude Code
**Arguments not working:**
- Verify `$1`, `$2` syntax correct
- Check `argument-hint` matches usage
- Ensure no extra spaces
**Bash execution failing:**
- Check `allowed-tools` includes Bash
- Verify command syntax in backticks
- Test command in terminal first
- Check for required permissions
**File references not working:**
- Verify `@` syntax correct
- Check file path is valid
- Ensure Read tool allowed
- Use absolute or project-relative paths
## Plugin-Specific Features
### CLAUDE_PLUGIN_ROOT Variable
Plugin commands have access to `${CLAUDE_PLUGIN_ROOT}`, an environment variable that resolves to the plugin's absolute path.
**Purpose:**
- Reference plugin files portably
- Execute plugin scripts
- Load plugin configuration
- Access plugin templates
**Basic usage:**
```markdown
---
description: Analyze using plugin script
allowed-tools: Bash(node:*)
---
Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1`
Review results and report findings.
```
**Common patterns:**
```markdown
# Execute plugin script
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh`
# Load plugin configuration
@${CLAUDE_PLUGIN_ROOT}/config/settings.json
# Use plugin template
@${CLAUDE_PLUGIN_ROOT}/templates/report.md
# Access plugin resources
@${CLAUDE_PLUGIN_ROOT}/docs/reference.md
```
**Why use it:**
- Works across all installations
- Portable between systems
- No hardcoded paths needed
- Essential for multi-file plugins
### Plugin Command Organization
Plugin commands discovered automatically from `commands/` directory:
```
plugin-name/
├── commands/
│ ├── foo.md # /foo (plugin:plugin-name)
│ ├── bar.md # /bar (plugin:plugin-name)
│ └── utils/
│ └── helper.md # /helper (plugin:plugin-name:utils)
└── plugin.json
```
**Namespace benefits:**
- Logical command grouping
- Shown in `/help` output
- Avoid name conflicts
- Organize related commands
**Naming conventions:**
- Use descriptive action names
- Avoid generic names (test, run)
- Consider plugin-specific prefix
- Use hyphens for multi-word names
### Plugin Command Patterns
**Configuration-based pattern:**
```markdown
---
description: Deploy using plugin configuration
argument-hint: [environment]
allowed-tools: Read, Bash(*)
---
Load configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json
Deploy to $1 using configuration settings.
Monitor deployment and report status.
```
**Template-based pattern:**
```markdown
---
description: Generate docs from template
argument-hint: [component]
---
Template: @${CLAUDE_PLUGIN_ROOT}/templates/docs.md
Generate documentation for $1 following template structure.
```
**Multi-script pattern:**
```text
---
description: Complete build workflow
allowed-tools: Bash(*)
---
# Example commands (remove # to use):
# Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh`
# Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh`
# Package: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh`
Review outputs and report workflow status.
```
**See `references/plugin-features-reference.md` for detailed patterns.**
## Integration with Plugin Components
Commands can integrate with other plugin components for powerful workflows.
### Agent Integration
Launch plugin agents for complex tasks:
```markdown
---
description: Deep code review
argument-hint: [file-path]
---
Initiate comprehensive review of @$1 using the code-reviewer agent.
The agent will analyze:
- Code structure
- Security issues
- Performance
- Best practices
Agent uses plugin resources:
- ${CLAUDE_PLUGIN_ROOT}/config/rules.json
- ${CLAUDE_PLUGIN_ROOT}/checklists/review.md
```
**Key points:**
- Agent must exist in `plugin/agents/` directory
- Claude uses Task tool to launch agent
- Document agent capabilities
- Reference plugin resources agent uses
### Skill Integration
Leverage plugin skills for specialized knowledge:
```markdown
---
description: Document API with standards
argument-hint: [api-file]
---
Document API in @$1 following plugin standards.
Use the api-docs-standards skill to ensure:
- Complete endpoint documentation
- Consistent formatting
- Example quality
- Error documentation
Generate production-ready API docs.
```
**Key points:**
- Skill must exist in `plugin/skills/` directory
- Mention skill name to trigger invocation
- Document skill purpose
- Explain what skill provides
### Hook Coordination
Design commands that work with plugin hooks:
- Commands can prepare state for hooks to process
- Hooks execute automatically on tool events
- Commands should document expected hook behavior
- Guide Claude on interpreting hook output
See `references/plugin-features-reference.md` for examples of commands that coordinate with hooks
### Multi-Component Workflows
Combine agents, skills, and scripts:
```markdown
---
description: Comprehensive review workflow
argument-hint: [file]
allowed-tools: Bash(node:*), Read
---
Target: @$1
Phase 1 - Static Analysis:
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1`
Phase 2 - Deep Review:
Launch code-reviewer agent for detailed analysis.
Phase 3 - Standards Check:
Use coding-standards skill for validation.
Phase 4 - Report:
Template: @${CLAUDE_PLUGIN_ROOT}/templates/review.md
Compile findings into report following template.
```
**When to use:**
- Complex multi-step workflows
- Leverage multiple plugin capabilities
- Require specialized analysis
- Need structured outputs
## Validation Patterns
Commands should validate inputs and resources before processing.
### Argument Validation
```markdown
---
description: Deploy with validation
argument-hint: [environment]
---
Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"`
If $1 is valid environment:
Deploy to $1
Otherwise:
Explain valid environments: dev, staging, prod
Show usage: /deploy [environment]
```
### File Existence Checks
```markdown
---
description: Process configuration
argument-hint: [config-file]
---
Check file exists: !`test -f $1 && echo "EXISTS" || echo "MISSING"`
If file exists:
Process configuration: @$1
Otherwise:
Explain where to place config file
Show expected format
Provide example configuration
```
### Plugin Resource Validation
```markdown
---
description: Run plugin analyzer
allowed-tools: Bash(test:*)
---
Validate plugin setup:
- Script: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"`
- Config: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"`
If all checks pass, run analysis.
Otherwise, report missing components.
```
### Error Handling
```markdown
---
description: Build with error handling
allowed-tools: Bash(*)
---
Execute build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh 2>&1 || echo "BUILD_FAILED"`
If build succeeded:
Report success and output location
If build failed:
Analyze error output
Suggest likely causes
Provide troubleshooting steps
```
**Best practices:**
- Validate early in command
- Provide helpful error messages
- Suggest corrective actions
- Handle edge cases gracefully
---
For detailed frontmatter field specifications, see `references/frontmatter-reference.md`.
For plugin-specific features and patterns, see `references/plugin-features-reference.md`.
For command pattern examples, see `examples/` directory.

View File

@@ -0,0 +1,557 @@
# Plugin Command Examples
Practical examples of commands designed for Claude Code plugins, demonstrating plugin-specific patterns and features.
## Table of Contents
1. [Simple Plugin Command](#1-simple-plugin-command)
2. [Script-Based Analysis](#2-script-based-analysis)
3. [Template-Based Generation](#3-template-based-generation)
4. [Multi-Script Workflow](#4-multi-script-workflow)
5. [Configuration-Driven Deployment](#5-configuration-driven-deployment)
6. [Agent Integration](#6-agent-integration)
7. [Skill Integration](#7-skill-integration)
8. [Multi-Component Workflow](#8-multi-component-workflow)
9. [Validated Input Command](#9-validated-input-command)
10. [Environment-Aware Command](#10-environment-aware-command)
---
## 1. Simple Plugin Command
**Use case:** Basic command that uses plugin script
**File:** `commands/analyze.md`
```markdown
---
description: Analyze code quality using plugin tools
argument-hint: [file-path]
allowed-tools: Bash(node:*), Read
---
Analyze @$1 using plugin's quality checker:
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/quality-check.js $1`
Review the analysis output and provide:
1. Summary of findings
2. Priority issues to address
3. Suggested improvements
4. Code quality score interpretation
```
**Key features:**
- Uses `${CLAUDE_PLUGIN_ROOT}` for portable path
- Combines file reference with script execution
- Simple single-purpose command
---
## 2. Script-Based Analysis
**Use case:** Run comprehensive analysis using multiple plugin scripts
**File:** `commands/full-audit.md`
```markdown
---
description: Complete code audit using plugin suite
argument-hint: [directory]
allowed-tools: Bash(*)
model: sonnet
---
Running complete audit on $1:
**Security scan:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/security-scan.sh $1`
**Performance analysis:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/perf-analyze.sh $1`
**Best practices check:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/best-practices.sh $1`
Analyze all results and create comprehensive report including:
- Critical issues requiring immediate attention
- Performance optimization opportunities
- Security vulnerabilities and fixes
- Overall health score and recommendations
```
**Key features:**
- Multiple script executions
- Organized output sections
- Comprehensive workflow
- Clear reporting structure
---
## 3. Template-Based Generation
**Use case:** Generate documentation following plugin template
**File:** `commands/gen-api-docs.md`
```markdown
---
description: Generate API documentation from template
argument-hint: [api-file]
---
Template structure: @${CLAUDE_PLUGIN_ROOT}/templates/api-documentation.md
API implementation: @$1
Generate complete API documentation following the template format above.
Ensure documentation includes:
- Endpoint descriptions with HTTP methods
- Request/response schemas
- Authentication requirements
- Error codes and handling
- Usage examples with curl commands
- Rate limiting information
Format output as markdown suitable for README or docs site.
```
**Key features:**
- Uses plugin template
- Combines template with source file
- Standardized output format
- Clear documentation structure
---
## 4. Multi-Script Workflow
**Use case:** Orchestrate build, test, and deploy workflow
**File:** `commands/release.md`
```markdown
---
description: Execute complete release workflow
argument-hint: [version]
allowed-tools: Bash(*), Read
---
Executing release workflow for version $1:
**Step 1 - Pre-release validation:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/pre-release-check.sh $1`
**Step 2 - Build artifacts:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build-release.sh $1`
**Step 3 - Run test suite:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/run-tests.sh`
**Step 4 - Package release:**
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/package.sh $1`
Review all step outputs and report:
1. Any failures or warnings
2. Build artifacts location
3. Test results summary
4. Next steps for deployment
5. Rollback plan if needed
```
**Key features:**
- Multi-step workflow
- Sequential script execution
- Clear step numbering
- Comprehensive reporting
---
## 5. Configuration-Driven Deployment
**Use case:** Deploy using environment-specific plugin configuration
**File:** `commands/deploy.md`
```markdown
---
description: Deploy application to environment
argument-hint: [environment]
allowed-tools: Read, Bash(*)
---
Deployment configuration for $1: @${CLAUDE_PLUGIN_ROOT}/config/$1-deploy.json
Current git state: !`git rev-parse --short HEAD`
Build info: !`cat package.json | grep -E '(name|version)'`
Execute deployment to $1 environment using configuration above.
Deployment checklist:
1. Validate configuration settings
2. Build application for $1
3. Run pre-deployment tests
4. Deploy to target environment
5. Run smoke tests
6. Verify deployment success
7. Update deployment log
Report deployment status and any issues encountered.
```
**Key features:**
- Environment-specific configuration
- Dynamic config file loading
- Pre-deployment validation
- Structured checklist
---
## 6. Agent Integration
**Use case:** Command that launches plugin agent for complex task
**File:** `commands/deep-review.md`
```markdown
---
description: Deep code review using plugin agent
argument-hint: [file-or-directory]
---
Initiate comprehensive code review of @$1 using the code-reviewer agent.
The agent will perform:
1. **Static analysis** - Check for code smells and anti-patterns
2. **Security audit** - Identify potential vulnerabilities
3. **Performance review** - Find optimization opportunities
4. **Best practices** - Ensure code follows standards
5. **Documentation check** - Verify adequate documentation
The agent has access to:
- Plugin's linting rules: ${CLAUDE_PLUGIN_ROOT}/config/lint-rules.json
- Security checklist: ${CLAUDE_PLUGIN_ROOT}/checklists/security.md
- Performance guidelines: ${CLAUDE_PLUGIN_ROOT}/docs/performance.md
Note: This uses the Task tool to launch the plugin's code-reviewer agent for thorough analysis.
```
**Key features:**
- Delegates to plugin agent
- Documents agent capabilities
- References plugin resources
- Clear scope definition
---
## 7. Skill Integration
**Use case:** Command that leverages plugin skill for specialized knowledge
**File:** `commands/document-api.md`
```markdown
---
description: Document API following plugin standards
argument-hint: [api-file]
---
API source code: @$1
Generate API documentation following the plugin's API documentation standards.
Use the api-documentation-standards skill to ensure:
- **OpenAPI compliance** - Follow OpenAPI 3.0 specification
- **Consistent formatting** - Use plugin's documentation style
- **Complete coverage** - Document all endpoints and schemas
- **Example quality** - Provide realistic usage examples
- **Error documentation** - Cover all error scenarios
The skill provides:
- Standard documentation templates
- API documentation best practices
- Common patterns for this codebase
- Quality validation criteria
Generate production-ready API documentation.
```
**Key features:**
- Invokes plugin skill by name
- Documents skill purpose
- Clear expectations
- Leverages skill knowledge
---
## 8. Multi-Component Workflow
**Use case:** Complex workflow using agents, skills, and scripts
**File:** `commands/complete-review.md`
```markdown
---
description: Comprehensive review using all plugin components
argument-hint: [file-path]
allowed-tools: Bash(node:*), Read
---
Target file: @$1
Execute comprehensive review workflow:
**Phase 1: Automated Analysis**
Run plugin analyzer: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js $1`
**Phase 2: Deep Review (Agent)**
Launch the code-quality-reviewer agent for detailed analysis.
Agent will examine:
- Code structure and organization
- Error handling patterns
- Testing coverage
- Documentation quality
**Phase 3: Standards Check (Skill)**
Use the coding-standards skill to validate:
- Naming conventions
- Code formatting
- Best practices adherence
- Framework-specific patterns
**Phase 4: Report Generation**
Template: @${CLAUDE_PLUGIN_ROOT}/templates/review-report.md
Compile all findings into comprehensive report following template.
**Phase 5: Recommendations**
Generate prioritized action items:
1. Critical issues (must fix)
2. Important improvements (should fix)
3. Nice-to-have enhancements (could fix)
Include specific file locations and suggested changes for each item.
```
**Key features:**
- Multi-phase workflow
- Combines scripts, agents, skills
- Template-based reporting
- Prioritized outputs
---
## 9. Validated Input Command
**Use case:** Command with input validation and error handling
**File:** `commands/build-env.md`
```markdown
---
description: Build for specific environment with validation
argument-hint: [environment]
allowed-tools: Bash(*)
---
Validate environment argument: !`echo "$1" | grep -E "^(dev|staging|prod)$" && echo "VALID" || echo "INVALID"`
Check build script exists: !`test -x ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh && echo "EXISTS" || echo "MISSING"`
Verify configuration available: !`test -f ${CLAUDE_PLUGIN_ROOT}/config/$1.json && echo "FOUND" || echo "NOT_FOUND"`
If all validations pass:
**Configuration:** @${CLAUDE_PLUGIN_ROOT}/config/$1.json
**Execute build:** !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh $1 2>&1`
**Validation results:** !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate-build.sh $1 2>&1`
Report build status and any issues.
If validations fail:
- Explain which validation failed
- Provide expected values/locations
- Suggest corrective actions
- Document troubleshooting steps
```
**Key features:**
- Input validation
- Resource existence checks
- Error handling
- Helpful error messages
- Graceful failure handling
---
## 10. Environment-Aware Command
**Use case:** Command that adapts behavior based on environment
**File:** `commands/run-checks.md`
```markdown
---
description: Run environment-appropriate checks
argument-hint: [environment]
allowed-tools: Bash(*), Read
---
Environment: $1
Load environment configuration: @${CLAUDE_PLUGIN_ROOT}/config/$1-checks.json
Determine check level: !`echo "$1" | grep -E "^prod$" && echo "FULL" || echo "BASIC"`
**For production environment:**
- Full test suite: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test-full.sh`
- Security scan: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/security-scan.sh`
- Performance audit: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/perf-check.sh`
- Compliance check: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/compliance.sh`
**For non-production environments:**
- Basic tests: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test-basic.sh`
- Quick lint: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/lint.sh`
Analyze results based on environment requirements:
**Production:** All checks must pass with zero critical issues
**Staging:** No critical issues, warnings acceptable
**Development:** Focus on blocking issues only
Report status and recommend proceed/block decision.
```
**Key features:**
- Environment-aware logic
- Conditional execution
- Different validation levels
- Appropriate reporting per environment
---
## Common Patterns Summary
### Pattern: Plugin Script Execution
```markdown
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/script-name.js $1`
```
Use for: Running plugin-provided Node.js scripts
### Pattern: Plugin Configuration Loading
```markdown
@${CLAUDE_PLUGIN_ROOT}/config/config-name.json
```
Use for: Loading plugin configuration files
### Pattern: Plugin Template Usage
```markdown
@${CLAUDE_PLUGIN_ROOT}/templates/template-name.md
```
Use for: Using plugin templates for generation
### Pattern: Agent Invocation
```markdown
Launch the [agent-name] agent for [task description].
```
Use for: Delegating complex tasks to plugin agents
### Pattern: Skill Reference
```markdown
Use the [skill-name] skill to ensure [requirements].
```
Use for: Leveraging plugin skills for specialized knowledge
### Pattern: Input Validation
```markdown
Validate input: !`echo "$1" | grep -E "^pattern$" && echo "OK" || echo "ERROR"`
```
Use for: Validating command arguments
### Pattern: Resource Validation
```markdown
Check exists: !`test -f ${CLAUDE_PLUGIN_ROOT}/path/file && echo "YES" || echo "NO"`
```
Use for: Verifying required plugin files exist
---
## Development Tips
### Testing Plugin Commands
1. **Test with plugin installed:**
```bash
cd /path/to/plugin
claude /command-name args
```
2. **Verify ${CLAUDE_PLUGIN_ROOT} expansion:**
```bash
# Add debug output to command
!`echo "Plugin root: ${CLAUDE_PLUGIN_ROOT}"`
```
3. **Test across different working directories:**
```bash
cd /tmp && claude /command-name
cd /other/project && claude /command-name
```
4. **Validate resource availability:**
```bash
# Check all plugin resources exist
!`ls -la ${CLAUDE_PLUGIN_ROOT}/scripts/`
!`ls -la ${CLAUDE_PLUGIN_ROOT}/config/`
```
### Common Mistakes to Avoid
1. **Using relative paths instead of ${CLAUDE_PLUGIN_ROOT}:**
```markdown
# Wrong
!`node ./scripts/analyze.js`
# Correct
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js`
```
2. **Forgetting to allow required tools:**
```markdown
# Missing allowed-tools
!`bash script.sh` # Will fail without Bash permission
# Correct
---
allowed-tools: Bash(*)
---
!`bash ${CLAUDE_PLUGIN_ROOT}/scripts/script.sh`
```
3. **Not validating inputs:**
```markdown
# Risky - no validation
Deploy to $1 environment
# Better - with validation
Validate: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"`
Deploy to $1 environment (if valid)
```
4. **Hardcoding plugin paths:**
```markdown
# Wrong - breaks on different installations
@/home/user/.claude/plugins/my-plugin/config.json
# Correct - works everywhere
@${CLAUDE_PLUGIN_ROOT}/config.json
```
---
For detailed plugin-specific features, see `references/plugin-features-reference.md`.
For general command development, see main `SKILL.md`.

View File

@@ -0,0 +1,504 @@
# Simple Command Examples
Basic slash command patterns for common use cases.
**Important:** All examples below are written as instructions FOR Claude (agent consumption), not messages TO users. Commands tell Claude what to do, not tell users what will happen.
## Example 1: Code Review Command
**File:** `.claude/commands/review.md`
```markdown
---
description: Review code for quality and issues
allowed-tools: Read, Bash(git:*)
---
Review the code in this repository for:
1. **Code Quality:**
- Readability and maintainability
- Consistent style and formatting
- Appropriate abstraction levels
2. **Potential Issues:**
- Logic errors or bugs
- Edge cases not handled
- Performance concerns
3. **Best Practices:**
- Design patterns used correctly
- Error handling present
- Documentation adequate
Provide specific feedback with file and line references.
```
**Usage:**
```
> /review
```
---
## Example 2: Security Review Command
**File:** `.claude/commands/security-review.md`
```markdown
---
description: Review code for security vulnerabilities
allowed-tools: Read, Grep
model: sonnet
---
Perform comprehensive security review checking for:
**Common Vulnerabilities:**
- SQL injection risks
- Cross-site scripting (XSS)
- Authentication/authorization issues
- Insecure data handling
- Hardcoded secrets or credentials
**Security Best Practices:**
- Input validation present
- Output encoding correct
- Secure defaults used
- Error messages safe
- Logging appropriate (no sensitive data)
For each issue found:
- File and line number
- Severity (Critical/High/Medium/Low)
- Description of vulnerability
- Recommended fix
Prioritize issues by severity.
```
**Usage:**
```
> /security-review
```
---
## Example 3: Test Command with File Argument
**File:** `.claude/commands/test-file.md`
```markdown
---
description: Run tests for specific file
argument-hint: [test-file]
allowed-tools: Bash(npm:*), Bash(jest:*)
---
Run tests for $1:
Test execution: !`npm test $1`
Analyze results:
- Tests passed/failed
- Code coverage
- Performance issues
- Flaky tests
If failures found, suggest fixes based on error messages.
```
**Usage:**
```
> /test-file src/utils/helpers.test.ts
```
---
## Example 4: Documentation Generator
**File:** `.claude/commands/document.md`
```markdown
---
description: Generate documentation for file
argument-hint: [source-file]
---
Generate comprehensive documentation for @$1
Include:
**Overview:**
- Purpose and responsibility
- Main functionality
- Dependencies
**API Documentation:**
- Function/method signatures
- Parameter descriptions with types
- Return values with types
- Exceptions/errors thrown
**Usage Examples:**
- Basic usage
- Common patterns
- Edge cases
**Implementation Notes:**
- Algorithm complexity
- Performance considerations
- Known limitations
Format as Markdown suitable for project documentation.
```
**Usage:**
```
> /document src/api/users.ts
```
---
## Example 5: Git Status Summary
**File:** `.claude/commands/git-status.md`
```markdown
---
description: Summarize Git repository status
allowed-tools: Bash(git:*)
---
Repository Status Summary:
**Current Branch:** !`git branch --show-current`
**Status:** !`git status --short`
**Recent Commits:** !`git log --oneline -5`
**Remote Status:** !`git fetch && git status -sb`
Provide:
- Summary of changes
- Suggested next actions
- Any warnings or issues
```
**Usage:**
```
> /git-status
```
---
## Example 6: Deployment Command
**File:** `.claude/commands/deploy.md`
```markdown
---
description: Deploy to specified environment
argument-hint: [environment] [version]
allowed-tools: Bash(kubectl:*), Read
---
Deploy to $1 environment using version $2
**Pre-deployment Checks:**
1. Verify $1 configuration exists
2. Check version $2 is valid
3. Verify cluster accessibility: !`kubectl cluster-info`
**Deployment Steps:**
1. Update deployment manifest with version $2
2. Apply configuration to $1
3. Monitor rollout status
4. Verify pod health
5. Run smoke tests
**Rollback Plan:**
Document current version for rollback if issues occur.
Proceed with deployment? (yes/no)
```
**Usage:**
```
> /deploy staging v1.2.3
```
---
## Example 7: Comparison Command
**File:** `.claude/commands/compare-files.md`
```markdown
---
description: Compare two files
argument-hint: [file1] [file2]
---
Compare @$1 with @$2
**Analysis:**
1. **Differences:**
- Lines added
- Lines removed
- Lines modified
2. **Functional Changes:**
- Breaking changes
- New features
- Bug fixes
- Refactoring
3. **Impact:**
- Affected components
- Required updates elsewhere
- Migration requirements
4. **Recommendations:**
- Code review focus areas
- Testing requirements
- Documentation updates needed
Present as structured comparison report.
```
**Usage:**
```
> /compare-files src/old-api.ts src/new-api.ts
```
---
## Example 8: Quick Fix Command
**File:** `.claude/commands/quick-fix.md`
```markdown
---
description: Quick fix for common issues
argument-hint: [issue-description]
model: haiku
---
Quickly fix: $ARGUMENTS
**Approach:**
1. Identify the issue
2. Find relevant code
3. Propose fix
4. Explain solution
Focus on:
- Simple, direct solution
- Minimal changes
- Following existing patterns
- No breaking changes
Provide code changes with file paths and line numbers.
```
**Usage:**
```
> /quick-fix button not responding to clicks
> /quick-fix typo in error message
```
---
## Example 9: Research Command
**File:** `.claude/commands/research.md`
```markdown
---
description: Research best practices for topic
argument-hint: [topic]
model: sonnet
---
Research best practices for: $ARGUMENTS
**Coverage:**
1. **Current State:**
- How we currently handle this
- Existing implementations
2. **Industry Standards:**
- Common patterns
- Recommended approaches
- Tools and libraries
3. **Comparison:**
- Our approach vs standards
- Gaps or improvements needed
- Migration considerations
4. **Recommendations:**
- Concrete action items
- Priority and effort estimates
- Resources for implementation
Provide actionable guidance based on research.
```
**Usage:**
```
> /research error handling in async operations
> /research API authentication patterns
```
---
## Example 10: Explain Code Command
**File:** `.claude/commands/explain.md`
```markdown
---
description: Explain how code works
argument-hint: [file-or-function]
---
Explain @$1 in detail
**Explanation Structure:**
1. **Overview:**
- What it does
- Why it exists
- How it fits in system
2. **Step-by-Step:**
- Line-by-line walkthrough
- Key algorithms or logic
- Important details
3. **Inputs and Outputs:**
- Parameters and types
- Return values
- Side effects
4. **Edge Cases:**
- Error handling
- Special cases
- Limitations
5. **Usage Examples:**
- How to call it
- Common patterns
- Integration points
Explain at level appropriate for junior engineer.
```
**Usage:**
```
> /explain src/utils/cache.ts
> /explain AuthService.login
```
---
## Key Patterns
### Pattern 1: Read-Only Analysis
```markdown
---
allowed-tools: Read, Grep
---
Analyze but don't modify...
```
**Use for:** Code review, documentation, analysis
### Pattern 2: Git Operations
```markdown
---
allowed-tools: Bash(git:*)
---
!`git status`
Analyze and suggest...
```
**Use for:** Repository status, commit analysis
### Pattern 3: Single Argument
```markdown
---
argument-hint: [target]
---
Process $1...
```
**Use for:** File operations, targeted actions
### Pattern 4: Multiple Arguments
```markdown
---
argument-hint: [source] [target] [options]
---
Process $1 to $2 with $3...
```
**Use for:** Workflows, deployments, comparisons
### Pattern 5: Fast Execution
```markdown
---
model: haiku
---
Quick simple task...
```
**Use for:** Simple, repetitive commands
### Pattern 6: File Comparison
```markdown
Compare @$1 with @$2...
```
**Use for:** Diff analysis, migration planning
### Pattern 7: Context Gathering
```markdown
---
allowed-tools: Bash(git:*), Read
---
Context: !`git status`
Files: @file1 @file2
Analyze...
```
**Use for:** Informed decision making
## Tips for Writing Simple Commands
1. **Start basic:** Single responsibility, clear purpose
2. **Add complexity gradually:** Start without frontmatter
3. **Test incrementally:** Verify each feature works
4. **Use descriptive names:** Command name should indicate purpose
5. **Document arguments:** Always use argument-hint
6. **Provide examples:** Show usage in comments
7. **Handle errors:** Consider missing arguments or files

View File

@@ -0,0 +1,722 @@
# Advanced Workflow Patterns
Multi-step command sequences and composition patterns for complex workflows.
## Overview
Advanced workflows combine multiple commands, coordinate state across invocations, and create sophisticated automation sequences. These patterns enable building complex functionality from simple command building blocks.
## Multi-Step Command Patterns
### Sequential Workflow Command
Commands that guide users through multi-step processes:
```markdown
---
description: Complete PR review workflow
argument-hint: [pr-number]
allowed-tools: Bash(gh:*), Read, Grep
---
# PR Review Workflow for #$1
## Step 1: Fetch PR Details
!`gh pr view $1 --json title,body,author,files`
## Step 2: Review Files
Files changed: !`gh pr diff $1 --name-only`
For each file:
- Check code quality
- Verify tests exist
- Review documentation
## Step 3: Run Checks
Test status: !`gh pr checks $1`
Verify:
- All tests passing
- No merge conflicts
- CI/CD successful
## Step 4: Provide Feedback
Summarize:
- Issues found (critical/minor)
- Suggestions for improvement
- Approval recommendation
Would you like to:
1. Approve PR
2. Request changes
3. Leave comments only
Reply with your choice and I'll help complete the action.
```
**Key features:**
- Numbered steps for clarity
- Bash execution for context
- Decision points for user input
- Next action suggestions
### State-Carrying Workflow
Commands that maintain state between invocations:
```markdown
---
description: Initialize deployment workflow
allowed-tools: Write, Bash(git:*)
---
# Initialize Deployment
Creating deployment tracking file...
Current branch: !`git branch --show-current`
Latest commit: !`git log -1 --format=%H`
Deployment state saved to `.claude/deployment-state.local.md`:
\`\`\`markdown
---
initialized: true
branch: $(git branch --show-current)
commit: $(git log -1 --format=%H)
timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)
status: initialized
---
# Deployment Tracking
Branch: $(git branch --show-current)
Started: $(date)
Next steps:
1. Run tests: /deploy-test
2. Build: /deploy-build
3. Deploy: /deploy-execute
\`\`\`
State saved. Run `/deploy-test` to continue.
```
**Next command** (`/deploy-test`):
```markdown
---
description: Run deployment tests
allowed-tools: Read, Bash(npm:*)
---
Reading deployment state from `.claude/deployment-state.local.md`...
Running tests: !`npm test`
Updating state to 'tested'...
Tests complete. Run `/deploy-build` to continue.
```
**Pattern benefits:**
- Persistent state across commands
- Clear workflow progression
- Safety checkpoints
- Resume capability
### Conditional Workflow Branching
Commands that adapt based on conditions:
```markdown
---
description: Smart deployment workflow
argument-hint: [environment]
allowed-tools: Bash(git:*), Bash(npm:*), Read
---
# Deploy to $1
## Pre-flight Checks
Branch: !`git branch --show-current`
Status: !`git status --short`
**Checking conditions:**
1. Branch status:
- If main/master: Require approval
- If feature branch: Warning about target
- If hotfix: Fast-track process
2. Tests:
!`npm test`
- If tests fail: STOP - fix tests first
- If tests pass: Continue
3. Environment:
- If $1 = 'production': Extra validation
- If $1 = 'staging': Standard process
- If $1 = 'dev': Minimal checks
**Workflow decision:**
Based on above, proceeding with: [determined workflow]
[Conditional steps based on environment and status]
Ready to deploy? (yes/no)
```
## Command Composition Patterns
### Command Chaining
Commands designed to work together:
```markdown
---
description: Prepare for code review
---
# Prepare Code Review
Running preparation sequence:
1. Format code: /format-code
2. Run linter: /lint-code
3. Run tests: /test-all
4. Generate coverage: /coverage-report
5. Create review summary: /review-summary
This is a meta-command. After completing each step above,
I'll compile results and prepare comprehensive review materials.
Starting sequence...
```
**Individual commands** are simple:
- `/format-code` - Just formats
- `/lint-code` - Just lints
- `/test-all` - Just tests
**Composition command** orchestrates them.
### Pipeline Pattern
Commands that process output from previous commands:
```markdown
---
description: Analyze test failures
---
# Analyze Test Failures
## Step 1: Get test results
(Run /test-all first if not done)
Reading test output...
## Step 2: Categorize failures
- Flaky tests (random failures)
- Consistent failures
- New failures vs existing
## Step 3: Prioritize
Rank by:
- Impact (critical path vs edge case)
- Frequency (always fails vs sometimes)
- Effort (quick fix vs major work)
## Step 4: Generate fix plan
For each failure:
- Root cause hypothesis
- Suggested fix approach
- Estimated effort
Would you like me to:
1. Fix highest priority failure
2. Generate detailed fix plans for all
3. Create GitHub issues for each
```
### Parallel Execution Pattern
Commands that coordinate multiple simultaneous operations:
```markdown
---
description: Run comprehensive validation
allowed-tools: Bash(*), Read
---
# Comprehensive Validation
Running validations in parallel...
Starting:
- Code quality checks
- Security scanning
- Dependency audit
- Performance profiling
This will take 2-3 minutes. I'll monitor all processes
and report when complete.
[Poll each process and report progress]
All validations complete. Summary:
- Quality: PASS (0 issues)
- Security: WARN (2 minor issues)
- Dependencies: PASS
- Performance: PASS (baseline met)
Details:
[Collated results from all checks]
```
## Workflow State Management
### Using .local.md Files
Store workflow state in plugin-specific files:
```markdown
.claude/plugin-name-workflow.local.md:
---
workflow: deployment
stage: testing
started: 2025-01-15T10:30:00Z
environment: staging
branch: feature/new-api
commit: abc123def
tests_passed: false
build_complete: false
---
# Deployment Workflow State
Current stage: Testing
Started: 2025-01-15 10:30 UTC
Completed steps:
- ✅ Validation
- ✅ Branch check
- ⏳ Testing (in progress)
Pending steps:
- Build
- Deploy
- Smoke tests
```
**Reading state in commands:**
```markdown
---
description: Continue deployment workflow
allowed-tools: Read, Write
---
Reading workflow state from .claude/plugin-name-workflow.local.md...
Current stage: @.claude/plugin-name-workflow.local.md
[Parse YAML frontmatter to determine next step]
Next action based on state: [determined action]
```
### Workflow Recovery
Handle interrupted workflows:
```markdown
---
description: Resume deployment workflow
allowed-tools: Read
---
# Resume Deployment
Checking for interrupted workflow...
State file: @.claude/plugin-name-workflow.local.md
**Workflow found:**
- Started: [timestamp]
- Environment: [env]
- Last completed: [step]
**Recovery options:**
1. Resume from last step
2. Restart from beginning
3. Abort and clean up
Which would you like? (1/2/3)
```
## Workflow Coordination Patterns
### Cross-Command Communication
Commands that signal each other:
```markdown
---
description: Mark feature complete
allowed-tools: Write
---
# Mark Feature Complete
Writing completion marker...
Creating: .claude/feature-complete.flag
This signals other commands that feature is ready for:
- Integration testing (/integration-test will auto-detect)
- Documentation generation (/docs-generate will include)
- Release notes (/release-notes will add)
Feature marked complete.
```
**Other commands check for flag:**
```markdown
---
description: Generate release notes
allowed-tools: Read, Bash(git:*)
---
Checking for completed features...
if [ -f .claude/feature-complete.flag ]; then
Feature ready for release notes
fi
[Include in release notes]
```
### Workflow Locking
Prevent concurrent workflow execution:
```markdown
---
description: Start deployment
allowed-tools: Read, Write, Bash
---
# Start Deployment
Checking for active deployments...
if [ -f .claude/deployment.lock ]; then
ERROR: Deployment already in progress
Started: [timestamp from lock file]
Cannot start concurrent deployment.
Wait for completion or run /deployment-abort
Exit.
fi
Creating deployment lock...
Deployment started. Lock created.
[Proceed with deployment]
```
**Lock cleanup:**
```markdown
---
description: Complete deployment
allowed-tools: Write, Bash
---
Deployment complete.
Removing deployment lock...
rm .claude/deployment.lock
Ready for next deployment.
```
## Advanced Argument Handling
### Optional Arguments with Defaults
```markdown
---
description: Deploy with optional version
argument-hint: [environment] [version]
---
Environment: ${1:-staging}
Version: ${2:-latest}
Deploying ${2:-latest} to ${1:-staging}...
Note: Using defaults for missing arguments:
- Environment defaults to 'staging'
- Version defaults to 'latest'
```
### Argument Validation
```markdown
---
description: Deploy to validated environment
argument-hint: [environment]
---
Environment: $1
Validating environment...
valid_envs="dev staging production"
if ! echo "$valid_envs" | grep -w "$1" > /dev/null; then
ERROR: Invalid environment '$1'
Valid options: dev, staging, production
Exit.
fi
Environment validated. Proceeding...
```
### Argument Transformation
```markdown
---
description: Deploy with shorthand
argument-hint: [env-shorthand]
---
Input: $1
Expanding shorthand:
- d/dev → development
- s/stg → staging
- p/prod → production
case "$1" in
d|dev) ENV="development";;
s|stg) ENV="staging";;
p|prod) ENV="production";;
*) ENV="$1";;
esac
Deploying to: $ENV
```
## Error Handling in Workflows
### Graceful Failure
```markdown
---
description: Resilient deployment workflow
---
# Deployment Workflow
Running steps with error handling...
## Step 1: Tests
!`npm test`
if [ $? -ne 0 ]; then
ERROR: Tests failed
Options:
1. Fix tests and retry
2. Skip tests (NOT recommended)
3. Abort deployment
What would you like to do?
[Wait for user input before continuing]
fi
## Step 2: Build
[Continue only if Step 1 succeeded]
```
### Rollback on Failure
```markdown
---
description: Deployment with rollback
---
# Deploy with Rollback
Saving current state for rollback...
Previous version: !`current-version.sh`
Deploying new version...
!`deploy.sh`
if [ $? -ne 0 ]; then
DEPLOYMENT FAILED
Initiating automatic rollback...
!`rollback.sh`
Rolled back to previous version.
Check logs for failure details.
fi
Deployment complete.
```
### Checkpoint Recovery
```markdown
---
description: Workflow with checkpoints
---
# Multi-Stage Deployment
## Checkpoint 1: Validation
!`validate.sh`
echo "checkpoint:validation" >> .claude/deployment-checkpoints.log
## Checkpoint 2: Build
!`build.sh`
echo "checkpoint:build" >> .claude/deployment-checkpoints.log
## Checkpoint 3: Deploy
!`deploy.sh`
echo "checkpoint:deploy" >> .claude/deployment-checkpoints.log
If any step fails, resume with:
/deployment-resume [last-successful-checkpoint]
```
## Best Practices
### Workflow Design
1. **Clear progression**: Number steps, show current position
2. **Explicit state**: Don't rely on implicit state
3. **User control**: Provide decision points
4. **Error recovery**: Handle failures gracefully
5. **Progress indication**: Show what's done, what's pending
### Command Composition
1. **Single responsibility**: Each command does one thing well
2. **Composable design**: Commands work together easily
3. **Standard interfaces**: Consistent input/output formats
4. **Loose coupling**: Commands don't depend on each other's internals
### State Management
1. **Persistent state**: Use .local.md files
2. **Atomic updates**: Write complete state files atomically
3. **State validation**: Check state file format/completeness
4. **Cleanup**: Remove stale state files
5. **Documentation**: Document state file formats
### Error Handling
1. **Fail fast**: Detect errors early
2. **Clear messages**: Explain what went wrong
3. **Recovery options**: Provide clear next steps
4. **State preservation**: Keep state for recovery
5. **Rollback capability**: Support undoing changes
## Example: Complete Deployment Workflow
### Initialize Command
```markdown
---
description: Initialize deployment
argument-hint: [environment]
allowed-tools: Write, Bash(git:*)
---
# Initialize Deployment to $1
Creating workflow state...
\`\`\`yaml
---
workflow: deployment
environment: $1
branch: !`git branch --show-current`
commit: !`git rev-parse HEAD`
stage: initialized
timestamp: !`date -u +%Y-%m-%dT%H:%M:%SZ`
---
\`\`\`
Written to .claude/deployment-state.local.md
Next: Run /deployment-validate
```
### Validation Command
```markdown
---
description: Validate deployment
allowed-tools: Read, Bash
---
Reading state: @.claude/deployment-state.local.md
Running validation...
- Branch check: PASS
- Tests: PASS
- Build: PASS
Updating state to 'validated'...
Next: Run /deployment-execute
```
### Execution Command
```markdown
---
description: Execute deployment
allowed-tools: Read, Bash, Write
---
Reading state: @.claude/deployment-state.local.md
Executing deployment to [environment]...
!`deploy.sh [environment]`
Deployment complete.
Updating state to 'completed'...
Cleanup: /deployment-cleanup
```
### Cleanup Command
```markdown
---
description: Clean up deployment
allowed-tools: Bash
---
Removing deployment state...
rm .claude/deployment-state.local.md
Deployment workflow complete.
```
This complete workflow demonstrates state management, sequential execution, error handling, and clean separation of concerns across multiple commands.

View File

@@ -0,0 +1,739 @@
# Command Documentation Patterns
Strategies for creating self-documenting, maintainable commands with excellent user experience.
## Overview
Well-documented commands are easier to use, maintain, and distribute. Documentation should be embedded in the command itself, making it immediately accessible to users and maintainers.
## Self-Documenting Command Structure
### Complete Command Template
```markdown
---
description: Clear, actionable description under 60 chars
argument-hint: [arg1] [arg2] [optional-arg]
allowed-tools: Read, Bash(git:*)
model: sonnet
---
<!--
COMMAND: command-name
VERSION: 1.0.0
AUTHOR: Team Name
LAST UPDATED: 2025-01-15
PURPOSE:
Detailed explanation of what this command does and why it exists.
USAGE:
/command-name arg1 arg2
ARGUMENTS:
arg1: Description of first argument (required)
arg2: Description of second argument (optional, defaults to X)
EXAMPLES:
/command-name feature-branch main
→ Compares feature-branch with main
/command-name my-branch
→ Compares my-branch with current branch
REQUIREMENTS:
- Git repository
- Branch must exist
- Permissions to read repository
RELATED COMMANDS:
/other-command - Related functionality
/another-command - Alternative approach
TROUBLESHOOTING:
- If branch not found: Check branch name spelling
- If permission denied: Check repository access
CHANGELOG:
v1.0.0 (2025-01-15): Initial release
v0.9.0 (2025-01-10): Beta version
-->
# Command Implementation
[Command prompt content here...]
[Explain what will happen...]
[Guide user through steps...]
[Provide clear output...]
```
### Documentation Comment Sections
**PURPOSE**: Why the command exists
- Problem it solves
- Use cases
- When to use vs when not to use
**USAGE**: Basic syntax
- Command invocation pattern
- Required vs optional arguments
- Default values
**ARGUMENTS**: Detailed argument documentation
- Each argument described
- Type information
- Valid values/ranges
- Defaults
**EXAMPLES**: Concrete usage examples
- Common use cases
- Edge cases
- Expected outputs
**REQUIREMENTS**: Prerequisites
- Dependencies
- Permissions
- Environmental setup
**RELATED COMMANDS**: Connections
- Similar commands
- Complementary commands
- Alternative approaches
**TROUBLESHOOTING**: Common issues
- Known problems
- Solutions
- Workarounds
**CHANGELOG**: Version history
- What changed when
- Breaking changes highlighted
- Migration guidance
## In-Line Documentation Patterns
### Commented Sections
```markdown
---
description: Complex multi-step command
---
<!-- SECTION 1: VALIDATION -->
<!-- This section checks prerequisites before proceeding -->
Checking prerequisites...
- Git repository: !`git rev-parse --git-dir 2>/dev/null`
- Branch exists: [validation logic]
<!-- SECTION 2: ANALYSIS -->
<!-- Analyzes the differences between branches -->
Analyzing differences between $1 and $2...
[Analysis logic...]
<!-- SECTION 3: RECOMMENDATIONS -->
<!-- Provides actionable recommendations -->
Based on analysis, recommend:
[Recommendations...]
<!-- END: Next steps for user -->
```
### Inline Explanations
```markdown
---
description: Deployment command with inline docs
---
# Deploy to $1
## Pre-flight Checks
<!-- We check branch status to prevent deploying from wrong branch -->
Current branch: !`git branch --show-current`
<!-- Production deploys must come from main/master -->
if [ "$1" = "production" ] && [ "$(git branch --show-current)" != "main" ]; then
⚠️ WARNING: Not on main branch for production deploy
This is unusual. Confirm this is intentional.
fi
<!-- Test status ensures we don't deploy broken code -->
Running tests: !`npm test`
✓ All checks passed
## Deployment
<!-- Actual deployment happens here -->
<!-- Uses blue-green strategy for zero-downtime -->
Deploying to $1 environment...
[Deployment steps...]
<!-- Post-deployment verification -->
Verifying deployment health...
[Health checks...]
Deployment complete!
## Next Steps
<!-- Guide user on what to do after deployment -->
1. Monitor logs: /logs $1
2. Run smoke tests: /smoke-test $1
3. Notify team: /notify-deployment $1
```
### Decision Point Documentation
```markdown
---
description: Interactive deployment command
---
# Interactive Deployment
## Configuration Review
Target: $1
Current version: !`cat version.txt`
New version: $2
<!-- DECISION POINT: User confirms configuration -->
<!-- This pause allows user to verify everything is correct -->
<!-- We can't automatically proceed because deployment is risky -->
Review the above configuration.
**Continue with deployment?**
- Reply "yes" to proceed
- Reply "no" to cancel
- Reply "edit" to modify configuration
[Await user input before continuing...]
<!-- After user confirms, we proceed with deployment -->
<!-- All subsequent steps are automated -->
Proceeding with deployment...
```
## Help Text Patterns
### Built-in Help Command
Create a help subcommand for complex commands:
```markdown
---
description: Main command with help
argument-hint: [subcommand] [args]
---
# Command Processor
if [ "$1" = "help" ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
**Command Help**
USAGE:
/command [subcommand] [args]
SUBCOMMANDS:
init [name] Initialize new configuration
deploy [env] Deploy to environment
status Show current status
rollback Rollback last deployment
help Show this help
EXAMPLES:
/command init my-project
/command deploy staging
/command status
/command rollback
For detailed help on a subcommand:
/command [subcommand] --help
Exit.
fi
[Regular command processing...]
```
### Contextual Help
Provide help based on context:
```markdown
---
description: Context-aware command
argument-hint: [operation] [target]
---
# Context-Aware Operation
if [ -z "$1" ]; then
**No operation specified**
Available operations:
- analyze: Analyze target for issues
- fix: Apply automatic fixes
- report: Generate detailed report
Usage: /command [operation] [target]
Examples:
/command analyze src/
/command fix src/app.js
/command report
Run /command help for more details.
Exit.
fi
[Command continues if operation provided...]
```
## Error Message Documentation
### Helpful Error Messages
```markdown
---
description: Command with good error messages
---
# Validation Command
if [ -z "$1" ]; then
❌ ERROR: Missing required argument
The 'file-path' argument is required.
USAGE:
/validate [file-path]
EXAMPLE:
/validate src/app.js
Try again with a file path.
Exit.
fi
if [ ! -f "$1" ]; then
❌ ERROR: File not found: $1
The specified file does not exist or is not accessible.
COMMON CAUSES:
1. Typo in file path
2. File was deleted or moved
3. Insufficient permissions
SUGGESTIONS:
- Check spelling: $1
- Verify file exists: ls -la $(dirname "$1")
- Check permissions: ls -l "$1"
Exit.
fi
[Command continues if validation passes...]
```
### Error Recovery Guidance
```markdown
---
description: Command with recovery guidance
---
# Operation Command
Running operation...
!`risky-operation.sh`
if [ $? -ne 0 ]; then
❌ OPERATION FAILED
The operation encountered an error and could not complete.
WHAT HAPPENED:
The risky-operation.sh script returned a non-zero exit code.
WHAT THIS MEANS:
- Changes may be partially applied
- System may be in inconsistent state
- Manual intervention may be needed
RECOVERY STEPS:
1. Check operation logs: cat /tmp/operation.log
2. Verify system state: /check-state
3. If needed, rollback: /rollback-operation
4. Fix underlying issue
5. Retry operation: /retry-operation
NEED HELP?
- Check troubleshooting guide: /help troubleshooting
- Contact support with error code: ERR_OP_FAILED_001
Exit.
fi
```
## Usage Example Documentation
### Embedded Examples
```markdown
---
description: Command with embedded examples
---
# Feature Command
This command performs feature analysis with multiple options.
## Basic Usage
\`\`\`
/feature analyze src/
\`\`\`
Analyzes all files in src/ directory for feature usage.
## Advanced Usage
\`\`\`
/feature analyze src/ --detailed
\`\`\`
Provides detailed analysis including:
- Feature breakdown by file
- Usage patterns
- Optimization suggestions
## Use Cases
**Use Case 1: Quick overview**
\`\`\`
/feature analyze .
\`\`\`
Get high-level feature summary of entire project.
**Use Case 2: Specific directory**
\`\`\`
/feature analyze src/components
\`\`\`
Focus analysis on components directory only.
**Use Case 3: Comparison**
\`\`\`
/feature analyze src/ --compare baseline.json
\`\`\`
Compare current features against baseline.
---
Now processing your request...
[Command implementation...]
```
### Example-Driven Documentation
```markdown
---
description: Example-heavy command
---
# Transformation Command
## What This Does
Transforms data from one format to another.
## Examples First
### Example 1: JSON to YAML
**Input:** `data.json`
\`\`\`json
{"name": "test", "value": 42}
\`\`\`
**Command:** `/transform data.json yaml`
**Output:** `data.yaml`
\`\`\`yaml
name: test
value: 42
\`\`\`
### Example 2: CSV to JSON
**Input:** `data.csv`
\`\`\`csv
name,value
test,42
\`\`\`
**Command:** `/transform data.csv json`
**Output:** `data.json`
\`\`\`json
[{"name": "test", "value": "42"}]
\`\`\`
### Example 3: With Options
**Command:** `/transform data.json yaml --pretty --sort-keys`
**Result:** Formatted YAML with sorted keys
---
## Your Transformation
File: $1
Format: $2
[Perform transformation...]
```
## Maintenance Documentation
### Version and Changelog
```markdown
<!--
VERSION: 2.1.0
LAST UPDATED: 2025-01-15
AUTHOR: DevOps Team
CHANGELOG:
v2.1.0 (2025-01-15):
- Added support for YAML configuration
- Improved error messages
- Fixed bug with special characters in arguments
v2.0.0 (2025-01-01):
- BREAKING: Changed argument order
- BREAKING: Removed deprecated --old-flag
- Added new validation checks
- Migration guide: /migration-v2
v1.5.0 (2024-12-15):
- Added --verbose flag
- Improved performance by 50%
v1.0.0 (2024-12-01):
- Initial stable release
MIGRATION NOTES:
From v1.x to v2.0:
Old: /command arg1 arg2 --old-flag
New: /command arg2 arg1
The --old-flag is removed. Use --new-flag instead.
DEPRECATION WARNINGS:
- The --legacy-mode flag is deprecated as of v2.1.0
- Will be removed in v3.0.0 (estimated 2025-06-01)
- Use --modern-mode instead
KNOWN ISSUES:
- #123: Slow performance with large files (workaround: use --stream flag)
- #456: Special characters in Windows (fix planned for v2.2.0)
-->
```
### Maintenance Notes
```markdown
<!--
MAINTENANCE NOTES:
CODE STRUCTURE:
- Lines 1-50: Argument parsing and validation
- Lines 51-100: Main processing logic
- Lines 101-150: Output formatting
- Lines 151-200: Error handling
DEPENDENCIES:
- Requires git 2.x or later
- Uses jq for JSON processing
- Needs bash 4.0+ for associative arrays
PERFORMANCE:
- Fast path for small inputs (< 1MB)
- Streams large files to avoid memory issues
- Caches results in /tmp for 1 hour
SECURITY CONSIDERATIONS:
- Validates all inputs to prevent injection
- Uses allowed-tools to limit Bash access
- No credentials in command file
TESTING:
- Unit tests: tests/command-test.sh
- Integration tests: tests/integration/
- Manual test checklist: tests/manual-checklist.md
FUTURE IMPROVEMENTS:
- TODO: Add support for TOML format
- TODO: Implement parallel processing
- TODO: Add progress bar for large files
RELATED FILES:
- lib/parser.sh: Shared parsing logic
- lib/formatter.sh: Output formatting
- config/defaults.yml: Default configuration
-->
```
## README Documentation
Commands should have companion README files:
```markdown
# Command Name
Brief description of what the command does.
## Installation
This command is part of the [plugin-name] plugin.
Install with:
\`\`\`
/plugin install plugin-name
\`\`\`
## Usage
Basic usage:
\`\`\`
/command-name [arg1] [arg2]
\`\`\`
## Arguments
- `arg1`: Description (required)
- `arg2`: Description (optional, defaults to X)
## Examples
### Example 1: Basic Usage
\`\`\`
/command-name value1 value2
\`\`\`
Description of what happens.
### Example 2: Advanced Usage
\`\`\`
/command-name value1 --option
\`\`\`
Description of advanced feature.
## Configuration
Optional configuration file: `.claude/command-name.local.md`
\`\`\`markdown
---
default_arg: value
enable_feature: true
---
\`\`\`
## Requirements
- Git 2.x or later
- jq (for JSON processing)
- Node.js 14+ (optional, for advanced features)
## Troubleshooting
### Issue: Command not found
**Solution:** Ensure plugin is installed and enabled.
### Issue: Permission denied
**Solution:** Check file permissions and allowed-tools setting.
## Contributing
Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md).
## License
MIT License - See [LICENSE](LICENSE).
## Support
- Issues: https://github.com/user/plugin/issues
- Docs: https://docs.example.com
- Email: support@example.com
```
## Best Practices
### Documentation Principles
1. **Write for your future self**: Assume you'll forget details
2. **Examples before explanations**: Show, then tell
3. **Progressive disclosure**: Basic info first, details available
4. **Keep it current**: Update docs when code changes
5. **Test your docs**: Verify examples actually work
### Documentation Locations
1. **In command file**: Core usage, examples, inline explanations
2. **README**: Installation, configuration, troubleshooting
3. **Separate docs**: Detailed guides, tutorials, API reference
4. **Comments**: Implementation details for maintainers
### Documentation Style
1. **Clear and concise**: No unnecessary words
2. **Active voice**: "Run the command" not "The command can be run"
3. **Consistent terminology**: Use same terms throughout
4. **Formatted well**: Use headings, lists, code blocks
5. **Accessible**: Assume reader is beginner
### Documentation Maintenance
1. **Version everything**: Track what changed when
2. **Deprecate gracefully**: Warn before removing features
3. **Migration guides**: Help users upgrade
4. **Archive old docs**: Keep old versions accessible
5. **Review regularly**: Ensure docs match reality
## Documentation Checklist
Before releasing a command:
- [ ] Description in frontmatter is clear
- [ ] argument-hint documents all arguments
- [ ] Usage examples in comments
- [ ] Common use cases shown
- [ ] Error messages are helpful
- [ ] Requirements documented
- [ ] Related commands listed
- [ ] Changelog maintained
- [ ] Version number updated
- [ ] README created/updated
- [ ] Examples actually work
- [ ] Troubleshooting section complete
With good documentation, commands become self-service, reducing support burden and improving user experience.

View File

@@ -0,0 +1,463 @@
# Command Frontmatter Reference
Complete reference for YAML frontmatter fields in slash commands.
## Frontmatter Overview
YAML frontmatter is optional metadata at the start of command files:
```markdown
---
description: Brief description
allowed-tools: Read, Write
model: sonnet
argument-hint: [arg1] [arg2]
---
Command prompt content here...
```
All fields are optional. Commands work without any frontmatter.
## Field Specifications
### description
**Type:** String
**Required:** No
**Default:** First line of command prompt
**Max Length:** ~60 characters recommended for `/help` display
**Purpose:** Describes what the command does, shown in `/help` output
**Examples:**
```yaml
description: Review code for security issues
```
```yaml
description: Deploy to staging environment
```
```yaml
description: Generate API documentation
```
**Best practices:**
- Keep under 60 characters for clean display
- Start with verb (Review, Deploy, Generate)
- Be specific about what command does
- Avoid redundant "command" or "slash command"
**Good:**
- ✅ "Review PR for code quality and security"
- ✅ "Deploy application to specified environment"
- ✅ "Generate comprehensive API documentation"
**Bad:**
- ❌ "This command reviews PRs" (unnecessary "This command")
- ❌ "Review" (too vague)
- ❌ "A command that reviews pull requests for code quality, security issues, and best practices" (too long)
### allowed-tools
**Type:** String or Array of strings
**Required:** No
**Default:** Inherits from conversation permissions
**Purpose:** Restrict or specify which tools command can use
**Formats:**
**Single tool:**
```yaml
allowed-tools: Read
```
**Multiple tools (comma-separated):**
```yaml
allowed-tools: Read, Write, Edit
```
**Multiple tools (array):**
```yaml
allowed-tools:
- Read
- Write
- Bash(git:*)
```
**Tool Patterns:**
**Specific tools:**
```yaml
allowed-tools: Read, Grep, Edit
```
**Bash with command filter:**
```yaml
allowed-tools: Bash(git:*) # Only git commands
allowed-tools: Bash(npm:*) # Only npm commands
allowed-tools: Bash(docker:*) # Only docker commands
```
**All tools (not recommended):**
```yaml
allowed-tools: "*"
```
**When to use:**
1. **Security:** Restrict command to safe operations
```yaml
allowed-tools: Read, Grep # Read-only command
```
2. **Clarity:** Document required tools
```yaml
allowed-tools: Bash(git:*), Read
```
3. **Bash execution:** Enable bash command output
```yaml
allowed-tools: Bash(git status:*), Bash(git diff:*)
```
**Best practices:**
- Be as restrictive as possible
- Use command filters for Bash (e.g., `git:*` not `*`)
- Only specify when different from conversation permissions
- Document why specific tools are needed
### model
**Type:** String
**Required:** No
**Default:** Inherits from conversation
**Values:** `sonnet`, `opus`, `haiku`
**Purpose:** Specify which Claude model executes the command
**Examples:**
```yaml
model: haiku # Fast, efficient for simple tasks
```
```yaml
model: sonnet # Balanced performance (default)
```
```yaml
model: opus # Maximum capability for complex tasks
```
**When to use:**
**Use `haiku` for:**
- Simple, formulaic commands
- Fast execution needed
- Low complexity tasks
- Frequent invocations
```yaml
---
description: Format code file
model: haiku
---
```
**Use `sonnet` for:**
- Standard commands (default)
- Balanced speed/quality
- Most common use cases
```yaml
---
description: Review code changes
model: sonnet
---
```
**Use `opus` for:**
- Complex analysis
- Architectural decisions
- Deep code understanding
- Critical tasks
```yaml
---
description: Analyze system architecture
model: opus
---
```
**Best practices:**
- Omit unless specific need
- Use `haiku` for speed when possible
- Reserve `opus` for genuinely complex tasks
- Test with different models to find right balance
### argument-hint
**Type:** String
**Required:** No
**Default:** None
**Purpose:** Document expected arguments for users and autocomplete
**Format:**
```yaml
argument-hint: [arg1] [arg2] [optional-arg]
```
**Examples:**
**Single argument:**
```yaml
argument-hint: [pr-number]
```
**Multiple required arguments:**
```yaml
argument-hint: [environment] [version]
```
**Optional arguments:**
```yaml
argument-hint: [file-path] [options]
```
**Descriptive names:**
```yaml
argument-hint: [source-branch] [target-branch] [commit-message]
```
**Best practices:**
- Use square brackets `[]` for each argument
- Use descriptive names (not `arg1`, `arg2`)
- Indicate optional vs required in description
- Match order to positional arguments in command
- Keep concise but clear
**Examples by pattern:**
**Simple command:**
```yaml
---
description: Fix issue by number
argument-hint: [issue-number]
---
Fix issue #$1...
```
**Multi-argument:**
```yaml
---
description: Deploy to environment
argument-hint: [app-name] [environment] [version]
---
Deploy $1 to $2 using version $3...
```
**With options:**
```yaml
---
description: Run tests with options
argument-hint: [test-pattern] [options]
---
Run tests matching $1 with options: $2
```
### disable-model-invocation
**Type:** Boolean
**Required:** No
**Default:** false
**Purpose:** Prevent SlashCommand tool from programmatically invoking command
**Examples:**
```yaml
disable-model-invocation: true
```
**When to use:**
1. **Manual-only commands:** Commands requiring user judgment
```yaml
---
description: Approve deployment to production
disable-model-invocation: true
---
```
2. **Destructive operations:** Commands with irreversible effects
```yaml
---
description: Delete all test data
disable-model-invocation: true
---
```
3. **Interactive workflows:** Commands needing user input
```yaml
---
description: Walk through setup wizard
disable-model-invocation: true
---
```
**Default behavior (false):**
- Command available to SlashCommand tool
- Claude can invoke programmatically
- Still available for manual invocation
**When true:**
- Command only invokable by user typing `/command`
- Not available to SlashCommand tool
- Safer for sensitive operations
**Best practices:**
- Use sparingly (limits Claude's autonomy)
- Document why in command comments
- Consider if command should exist if always manual
## Complete Examples
### Minimal Command
No frontmatter needed:
```markdown
Review this code for common issues and suggest improvements.
```
### Simple Command
Just description:
```markdown
---
description: Review code for issues
---
Review this code for common issues and suggest improvements.
```
### Standard Command
Description and tools:
```markdown
---
description: Review Git changes
allowed-tools: Bash(git:*), Read
---
Current changes: !`git diff --name-only`
Review each changed file for:
- Code quality
- Potential bugs
- Best practices
```
### Complex Command
All common fields:
```markdown
---
description: Deploy application to environment
argument-hint: [app-name] [environment] [version]
allowed-tools: Bash(kubectl:*), Bash(helm:*), Read
model: sonnet
---
Deploy $1 to $2 environment using version $3
Pre-deployment checks:
- Verify $2 configuration
- Check cluster status: !`kubectl cluster-info`
- Validate version $3 exists
Proceed with deployment following deployment runbook.
```
### Manual-Only Command
Restricted invocation:
```markdown
---
description: Approve production deployment
argument-hint: [deployment-id]
disable-model-invocation: true
allowed-tools: Bash(gh:*)
---
<!--
MANUAL APPROVAL REQUIRED
This command requires human judgment and cannot be automated.
-->
Review deployment $1 for production approval:
Deployment details: !`gh api /deployments/$1`
Verify:
- All tests passed
- Security scan clean
- Stakeholder approval
- Rollback plan ready
Type "APPROVED" to confirm deployment.
```
## Validation
### Common Errors
**Invalid YAML syntax:**
```yaml
---
description: Missing quote
allowed-tools: Read, Write
model: sonnet
--- # ❌ Missing closing quote above
```
**Fix:** Validate YAML syntax
**Incorrect tool specification:**
```yaml
allowed-tools: Bash # ❌ Missing command filter
```
**Fix:** Use `Bash(git:*)` format
**Invalid model name:**
```yaml
model: gpt4 # ❌ Not a valid Claude model
```
**Fix:** Use `sonnet`, `opus`, or `haiku`
### Validation Checklist
Before committing command:
- [ ] YAML syntax valid (no errors)
- [ ] Description under 60 characters
- [ ] allowed-tools uses proper format
- [ ] model is valid value if specified
- [ ] argument-hint matches positional arguments
- [ ] disable-model-invocation used appropriately
## Best Practices Summary
1. **Start minimal:** Add frontmatter only when needed
2. **Document arguments:** Always use argument-hint with arguments
3. **Restrict tools:** Use most restrictive allowed-tools that works
4. **Choose right model:** Use haiku for speed, opus for complexity
5. **Manual-only sparingly:** Only use disable-model-invocation when necessary
6. **Clear descriptions:** Make commands discoverable in `/help`
7. **Test thoroughly:** Verify frontmatter works as expected

View File

@@ -0,0 +1,920 @@
# Interactive Command Patterns
Comprehensive guide to creating commands that gather user feedback and make decisions through the AskUserQuestion tool.
## Overview
Some commands need user input that doesn't work well with simple arguments. For example:
- Choosing between multiple complex options with trade-offs
- Selecting multiple items from a list
- Making decisions that require explanation
- Gathering preferences or configuration interactively
For these cases, use the **AskUserQuestion tool** within command execution rather than relying on command arguments.
## When to Use AskUserQuestion
### Use AskUserQuestion When:
1. **Multiple choice decisions** with explanations needed
2. **Complex options** that require context to choose
3. **Multi-select scenarios** (choosing multiple items)
4. **Preference gathering** for configuration
5. **Interactive workflows** that adapt based on answers
### Use Command Arguments When:
1. **Simple values** (file paths, numbers, names)
2. **Known inputs** user already has
3. **Scriptable workflows** that should be automatable
4. **Fast invocations** where prompting would slow down
## AskUserQuestion Basics
### Tool Parameters
```typescript
{
questions: [
{
question: "Which authentication method should we use?",
header: "Auth method", // Short label (max 12 chars)
multiSelect: false, // true for multiple selection
options: [
{
label: "OAuth 2.0",
description: "Industry standard, supports multiple providers"
},
{
label: "JWT",
description: "Stateless, good for APIs"
},
{
label: "Session",
description: "Traditional, server-side state"
}
]
}
]
}
```
**Key points:**
- Users can always choose "Other" to provide custom input (automatic)
- `multiSelect: true` allows selecting multiple options
- Options should be 2-4 choices (not more)
- Can ask 1-4 questions per tool call
## Command Pattern for User Interaction
### Basic Interactive Command
```markdown
---
description: Interactive setup command
allowed-tools: AskUserQuestion, Write
---
# Interactive Plugin Setup
This command will guide you through configuring the plugin with a series of questions.
## Step 1: Gather Configuration
Use the AskUserQuestion tool to ask:
**Question 1 - Deployment target:**
- header: "Deploy to"
- question: "Which deployment platform will you use?"
- options:
- AWS (Amazon Web Services with ECS/EKS)
- GCP (Google Cloud with GKE)
- Azure (Microsoft Azure with AKS)
- Local (Docker on local machine)
**Question 2 - Environment strategy:**
- header: "Environments"
- question: "How many environments do you need?"
- options:
- Single (Just production)
- Standard (Dev, Staging, Production)
- Complete (Dev, QA, Staging, Production)
**Question 3 - Features to enable:**
- header: "Features"
- question: "Which features do you want to enable?"
- multiSelect: true
- options:
- Auto-scaling (Automatic resource scaling)
- Monitoring (Health checks and metrics)
- CI/CD (Automated deployment pipeline)
- Backups (Automated database backups)
## Step 2: Process Answers
Based on the answers received from AskUserQuestion:
1. Parse the deployment target choice
2. Set up environment-specific configuration
3. Enable selected features
4. Generate configuration files
## Step 3: Generate Configuration
Create `.claude/plugin-name.local.md` with:
\`\`\`yaml
---
deployment_target: [answer from Q1]
environments: [answer from Q2]
features:
auto_scaling: [true if selected in Q3]
monitoring: [true if selected in Q3]
ci_cd: [true if selected in Q3]
backups: [true if selected in Q3]
---
# Plugin Configuration
Generated: [timestamp]
Target: [deployment_target]
Environments: [environments]
\`\`\`
## Step 4: Confirm and Next Steps
Confirm configuration created and guide user on next steps.
```
### Multi-Stage Interactive Workflow
```markdown
---
description: Multi-stage interactive workflow
allowed-tools: AskUserQuestion, Read, Write, Bash
---
# Multi-Stage Deployment Setup
This command walks through deployment setup in stages, adapting based on your answers.
## Stage 1: Basic Configuration
Use AskUserQuestion to ask about deployment basics.
Based on answers, determine which additional questions to ask.
## Stage 2: Advanced Options (Conditional)
If user selected "Advanced" deployment in Stage 1:
Use AskUserQuestion to ask about:
- Load balancing strategy
- Caching configuration
- Security hardening options
If user selected "Simple" deployment:
- Skip advanced questions
- Use sensible defaults
## Stage 3: Confirmation
Show summary of all selections.
Use AskUserQuestion for final confirmation:
- header: "Confirm"
- question: "Does this configuration look correct?"
- options:
- Yes (Proceed with setup)
- No (Start over)
- Modify (Let me adjust specific settings)
If "Modify", ask which specific setting to change.
## Stage 4: Execute Setup
Based on confirmed configuration, execute setup steps.
```
## Interactive Question Design
### Question Structure
**Good questions:**
```markdown
Question: "Which database should we use for this project?"
Header: "Database"
Options:
- PostgreSQL (Relational, ACID compliant, best for complex queries)
- MongoDB (Document store, flexible schema, best for rapid iteration)
- Redis (In-memory, fast, best for caching and sessions)
```
**Poor questions:**
```markdown
Question: "Database?" // Too vague
Header: "DB" // Unclear abbreviation
Options:
- Option 1 // Not descriptive
- Option 2
```
### Option Design Best Practices
**Clear labels:**
- Use 1-5 words
- Specific and descriptive
- No jargon without context
**Helpful descriptions:**
- Explain what the option means
- Mention key benefits or trade-offs
- Help user make informed decision
- Keep to 1-2 sentences
**Appropriate number:**
- 2-4 options per question
- Don't overwhelm with too many choices
- Group related options
- "Other" automatically provided
### Multi-Select Questions
**When to use multiSelect:**
```markdown
Use AskUserQuestion for enabling features:
Question: "Which features do you want to enable?"
Header: "Features"
multiSelect: true // Allow selecting multiple
Options:
- Logging (Detailed operation logs)
- Metrics (Performance monitoring)
- Alerts (Error notifications)
- Backups (Automatic backups)
```
User can select any combination: none, some, or all.
**When NOT to use multiSelect:**
```markdown
Question: "Which authentication method?"
multiSelect: false // Only one auth method makes sense
```
Mutually exclusive choices should not use multiSelect.
## Command Patterns with AskUserQuestion
### Pattern 1: Simple Yes/No Decision
```markdown
---
description: Command with confirmation
allowed-tools: AskUserQuestion, Bash
---
# Destructive Operation
This operation will delete all cached data.
Use AskUserQuestion to confirm:
Question: "This will delete all cached data. Are you sure?"
Header: "Confirm"
Options:
- Yes (Proceed with deletion)
- No (Cancel operation)
If user selects "Yes":
Execute deletion
Report completion
If user selects "No":
Cancel operation
Exit without changes
```
### Pattern 2: Multiple Configuration Questions
```markdown
---
description: Multi-question configuration
allowed-tools: AskUserQuestion, Write
---
# Project Configuration Setup
Gather configuration through multiple questions.
Use AskUserQuestion with multiple questions in one call:
**Question 1:**
- question: "Which programming language?"
- header: "Language"
- options: Python, TypeScript, Go, Rust
**Question 2:**
- question: "Which test framework?"
- header: "Testing"
- options: Jest, PyTest, Go Test, Cargo Test
(Adapt based on language from Q1)
**Question 3:**
- question: "Which CI/CD platform?"
- header: "CI/CD"
- options: GitHub Actions, GitLab CI, CircleCI
**Question 4:**
- question: "Which features do you need?"
- header: "Features"
- multiSelect: true
- options: Linting, Type checking, Code coverage, Security scanning
Process all answers together to generate cohesive configuration.
```
### Pattern 3: Conditional Question Flow
```markdown
---
description: Conditional interactive workflow
allowed-tools: AskUserQuestion, Read, Write
---
# Adaptive Configuration
## Question 1: Deployment Complexity
Use AskUserQuestion:
Question: "How complex is your deployment?"
Header: "Complexity"
Options:
- Simple (Single server, straightforward)
- Standard (Multiple servers, load balancing)
- Complex (Microservices, orchestration)
## Conditional Questions Based on Answer
If answer is "Simple":
- No additional questions
- Use minimal configuration
If answer is "Standard":
- Ask about load balancing strategy
- Ask about scaling policy
If answer is "Complex":
- Ask about orchestration platform (Kubernetes, Docker Swarm)
- Ask about service mesh (Istio, Linkerd, None)
- Ask about monitoring (Prometheus, Datadog, CloudWatch)
- Ask about logging aggregation
## Process Conditional Answers
Generate configuration appropriate for selected complexity level.
```
### Pattern 4: Iterative Collection
```markdown
---
description: Collect multiple items iteratively
allowed-tools: AskUserQuestion, Write
---
# Collect Team Members
We'll collect team member information for the project.
## Question: How many team members?
Use AskUserQuestion:
Question: "How many team members should we set up?"
Header: "Team size"
Options:
- 2 people
- 3 people
- 4 people
- 6 people
## Iterate Through Team Members
For each team member (1 to N based on answer):
Use AskUserQuestion for member details:
Question: "What role for team member [number]?"
Header: "Role"
Options:
- Frontend Developer
- Backend Developer
- DevOps Engineer
- QA Engineer
- Designer
Store each member's information.
## Generate Team Configuration
After collecting all N members, create team configuration file with all members and their roles.
```
### Pattern 5: Dependency Selection
```markdown
---
description: Select dependencies with multi-select
allowed-tools: AskUserQuestion
---
# Configure Project Dependencies
## Question: Required Libraries
Use AskUserQuestion with multiSelect:
Question: "Which libraries does your project need?"
Header: "Dependencies"
multiSelect: true
Options:
- React (UI framework)
- Express (Web server)
- TypeORM (Database ORM)
- Jest (Testing framework)
- Axios (HTTP client)
User can select any combination.
## Process Selections
For each selected library:
- Add to package.json dependencies
- Generate sample configuration
- Create usage examples
- Update documentation
```
## Best Practices for Interactive Commands
### Question Design
1. **Clear and specific**: Question should be unambiguous
2. **Concise header**: Max 12 characters for clean display
3. **Helpful options**: Labels are clear, descriptions explain trade-offs
4. **Appropriate count**: 2-4 options per question, 1-4 questions per call
5. **Logical order**: Questions flow naturally
### Error Handling
```markdown
# Handle AskUserQuestion Responses
After calling AskUserQuestion, verify answers received:
If answers are empty or invalid:
Something went wrong gathering responses.
Please try again or provide configuration manually:
[Show alternative approach]
Exit.
If answers look correct:
Process as expected
```
### Progressive Disclosure
```markdown
# Start Simple, Get Detailed as Needed
## Question 1: Setup Type
Use AskUserQuestion:
Question: "How would you like to set up?"
Header: "Setup type"
Options:
- Quick (Use recommended defaults)
- Custom (Configure all options)
- Guided (Step-by-step with explanations)
If "Quick":
Apply defaults, minimal questions
If "Custom":
Ask all available configuration questions
If "Guided":
Ask questions with extra explanation
Provide recommendations along the way
```
### Multi-Select Guidelines
**Good multi-select use:**
```markdown
Question: "Which features do you want to enable?"
multiSelect: true
Options:
- Logging
- Metrics
- Alerts
- Backups
Reason: User might want any combination
```
**Bad multi-select use:**
```markdown
Question: "Which database engine?"
multiSelect: true // ❌ Should be single-select
Reason: Can only use one database engine
```
## Advanced Patterns
### Validation Loop
```markdown
---
description: Interactive with validation
allowed-tools: AskUserQuestion, Bash
---
# Setup with Validation
## Gather Configuration
Use AskUserQuestion to collect settings.
## Validate Configuration
Check if configuration is valid:
- Required dependencies available?
- Settings compatible with each other?
- No conflicts detected?
If validation fails:
Show validation errors
Use AskUserQuestion to ask:
Question: "Configuration has issues. What would you like to do?"
Header: "Next step"
Options:
- Fix (Adjust settings to resolve issues)
- Override (Proceed despite warnings)
- Cancel (Abort setup)
Based on answer, retry or proceed or exit.
```
### Build Configuration Incrementally
```markdown
---
description: Incremental configuration builder
allowed-tools: AskUserQuestion, Write, Read
---
# Incremental Setup
## Phase 1: Core Settings
Use AskUserQuestion for core settings.
Save to `.claude/config-partial.yml`
## Phase 2: Review Core Settings
Show user the core settings:
Based on these core settings, you need to configure:
- [Setting A] (because you chose [X])
- [Setting B] (because you chose [Y])
Ready to continue?
## Phase 3: Detailed Settings
Use AskUserQuestion for settings based on Phase 1 answers.
Merge with core settings.
## Phase 4: Final Review
Present complete configuration.
Use AskUserQuestion for confirmation:
Question: "Is this configuration correct?"
Options:
- Yes (Save and apply)
- No (Start over)
- Modify (Edit specific settings)
```
### Dynamic Options Based on Context
```markdown
---
description: Context-aware questions
allowed-tools: AskUserQuestion, Bash, Read
---
# Context-Aware Setup
## Detect Current State
Check existing configuration:
- Current language: !`detect-language.sh`
- Existing frameworks: !`detect-frameworks.sh`
- Available tools: !`check-tools.sh`
## Ask Context-Appropriate Questions
Based on detected language, ask relevant questions.
If language is TypeScript:
Use AskUserQuestion:
Question: "Which TypeScript features should we enable?"
Options:
- Strict Mode (Maximum type safety)
- Decorators (Experimental decorator support)
- Path Mapping (Module path aliases)
If language is Python:
Use AskUserQuestion:
Question: "Which Python tools should we configure?"
Options:
- Type Hints (mypy for type checking)
- Black (Code formatting)
- Pylint (Linting and style)
Questions adapt to project context.
```
## Real-World Example: Multi-Agent Swarm Launch
**From multi-agent-swarm plugin:**
```markdown
---
description: Launch multi-agent swarm
allowed-tools: AskUserQuestion, Read, Write, Bash
---
# Launch Multi-Agent Swarm
## Interactive Mode (No Task List Provided)
If user didn't provide task list file, help create one interactively.
### Question 1: Agent Count
Use AskUserQuestion:
Question: "How many agents should we launch?"
Header: "Agent count"
Options:
- 2 agents (Best for simple projects)
- 3 agents (Good for medium projects)
- 4 agents (Standard team size)
- 6 agents (Large projects)
- 8 agents (Complex multi-component projects)
### Question 2: Task Definition Approach
Use AskUserQuestion:
Question: "How would you like to define tasks?"
Header: "Task setup"
Options:
- File (I have a task list file ready)
- Guided (Help me create tasks interactively)
- Custom (Other approach)
If "File":
Ask for file path
Validate file exists and has correct format
If "Guided":
Enter iterative task creation mode (see below)
### Question 3: Coordination Mode
Use AskUserQuestion:
Question: "How should agents coordinate?"
Header: "Coordination"
Options:
- Team Leader (One agent coordinates others)
- Collaborative (Agents coordinate as peers)
- Autonomous (Independent work, minimal coordination)
### Iterative Task Creation (If "Guided" Selected)
For each agent (1 to N from Question 1):
**Question A: Agent Name**
Question: "What should we call agent [number]?"
Header: "Agent name"
Options:
- auth-agent
- api-agent
- ui-agent
- db-agent
(Provide relevant suggestions based on common patterns)
**Question B: Task Type**
Question: "What task for [agent-name]?"
Header: "Task type"
Options:
- Authentication (User auth, JWT, OAuth)
- API Endpoints (REST/GraphQL APIs)
- UI Components (Frontend components)
- Database (Schema, migrations, queries)
- Testing (Test suites and coverage)
- Documentation (Docs, README, guides)
**Question C: Dependencies**
Question: "What does [agent-name] depend on?"
Header: "Dependencies"
multiSelect: true
Options:
- [List of previously defined agents]
- No dependencies
**Question D: Base Branch**
Question: "Which base branch for PR?"
Header: "PR base"
Options:
- main
- staging
- develop
Store all task information for each agent.
### Generate Task List File
After collecting all agent task details:
1. Ask for project name
2. Generate task list in proper format
3. Save to `.daisy/swarm/tasks.md`
4. Show user the file path
5. Proceed with launch using generated task list
```
## Best Practices
### Question Writing
1. **Be specific**: "Which database?" not "Choose option?"
2. **Explain trade-offs**: Describe pros/cons in option descriptions
3. **Provide context**: Question text should stand alone
4. **Guide decisions**: Help user make informed choice
5. **Keep concise**: Header max 12 chars, descriptions 1-2 sentences
### Option Design
1. **Meaningful labels**: Specific, clear names
2. **Informative descriptions**: Explain what each option does
3. **Show trade-offs**: Help user understand implications
4. **Consistent detail**: All options equally explained
5. **2-4 options**: Not too few, not too many
### Flow Design
1. **Logical order**: Questions flow naturally
2. **Build on previous**: Later questions use earlier answers
3. **Minimize questions**: Ask only what's needed
4. **Group related**: Ask related questions together
5. **Show progress**: Indicate where in flow
### User Experience
1. **Set expectations**: Tell user what to expect
2. **Explain why**: Help user understand purpose
3. **Provide defaults**: Suggest recommended options
4. **Allow escape**: Let user cancel or restart
5. **Confirm actions**: Summarize before executing
## Common Patterns
### Pattern: Feature Selection
```markdown
Use AskUserQuestion:
Question: "Which features do you need?"
Header: "Features"
multiSelect: true
Options:
- Authentication
- Authorization
- Rate Limiting
- Caching
```
### Pattern: Environment Configuration
```markdown
Use AskUserQuestion:
Question: "Which environment is this?"
Header: "Environment"
Options:
- Development (Local development)
- Staging (Pre-production testing)
- Production (Live environment)
```
### Pattern: Priority Selection
```markdown
Use AskUserQuestion:
Question: "What's the priority for this task?"
Header: "Priority"
Options:
- Critical (Must be done immediately)
- High (Important, do soon)
- Medium (Standard priority)
- Low (Nice to have)
```
### Pattern: Scope Selection
```markdown
Use AskUserQuestion:
Question: "What scope should we analyze?"
Header: "Scope"
Options:
- Current file (Just this file)
- Current directory (All files in directory)
- Entire project (Full codebase scan)
```
## Combining Arguments and Questions
### Use Both Appropriately
**Arguments for known values:**
```markdown
---
argument-hint: [project-name]
allowed-tools: AskUserQuestion, Write
---
Setup for project: $1
Now gather additional configuration...
Use AskUserQuestion for options that require explanation.
```
**Questions for complex choices:**
```markdown
Project name from argument: $1
Now use AskUserQuestion to choose:
- Architecture pattern
- Technology stack
- Deployment strategy
These require explanation, so questions work better than arguments.
```
## Troubleshooting
**Questions not appearing:**
- Verify AskUserQuestion in allowed-tools
- Check question format is correct
- Ensure options array has 2-4 items
**User can't make selection:**
- Check option labels are clear
- Verify descriptions are helpful
- Consider if too many options
- Ensure multiSelect setting is correct
**Flow feels confusing:**
- Reduce number of questions
- Group related questions
- Add explanation between stages
- Show progress through workflow
With AskUserQuestion, commands become interactive wizards that guide users through complex decisions while maintaining the clarity that simple arguments provide for straightforward inputs.

View File

@@ -0,0 +1,904 @@
# Marketplace Considerations for Commands
Guidelines for creating commands designed for distribution and marketplace success.
## Overview
Commands distributed through marketplaces need additional consideration beyond personal use commands. They must work across environments, handle diverse use cases, and provide excellent user experience for unknown users.
## Design for Distribution
### Universal Compatibility
**Cross-platform considerations:**
```markdown
---
description: Cross-platform command
allowed-tools: Bash(*)
---
# Platform-Aware Command
Detecting platform...
case "$(uname)" in
Darwin*) PLATFORM="macOS" ;;
Linux*) PLATFORM="Linux" ;;
MINGW*|MSYS*|CYGWIN*) PLATFORM="Windows" ;;
*) PLATFORM="Unknown" ;;
esac
Platform: $PLATFORM
<!-- Adjust behavior based on platform -->
if [ "$PLATFORM" = "Windows" ]; then
# Windows-specific handling
PATH_SEP="\\"
NULL_DEVICE="NUL"
else
# Unix-like handling
PATH_SEP="/"
NULL_DEVICE="/dev/null"
fi
[Platform-appropriate implementation...]
```
**Avoid platform-specific commands:**
```markdown
<!-- BAD: macOS-specific -->
!`pbcopy < file.txt`
<!-- GOOD: Platform detection -->
if command -v pbcopy > /dev/null; then
pbcopy < file.txt
elif command -v xclip > /dev/null; then
xclip -selection clipboard < file.txt
elif command -v clip.exe > /dev/null; then
cat file.txt | clip.exe
else
echo "Clipboard not available on this platform"
fi
```
### Minimal Dependencies
**Check for required tools:**
```markdown
---
description: Dependency-aware command
allowed-tools: Bash(*)
---
# Check Dependencies
Required tools:
- git
- jq
- node
Checking availability...
MISSING_DEPS=""
for tool in git jq node; do
if ! command -v $tool > /dev/null; then
MISSING_DEPS="$MISSING_DEPS $tool"
fi
done
if [ -n "$MISSING_DEPS" ]; then
❌ ERROR: Missing required dependencies:$MISSING_DEPS
INSTALLATION:
- git: https://git-scm.com/downloads
- jq: https://stedolan.github.io/jq/download/
- node: https://nodejs.org/
Install missing tools and try again.
Exit.
fi
✓ All dependencies available
[Continue with command...]
```
**Document optional dependencies:**
```markdown
<!--
DEPENDENCIES:
Required:
- git 2.0+: Version control
- jq 1.6+: JSON processing
Optional:
- gh: GitHub CLI (for PR operations)
- docker: Container operations (for containerized tests)
Feature availability depends on installed tools.
-->
```
### Graceful Degradation
**Handle missing features:**
```markdown
---
description: Feature-aware command
---
# Feature Detection
Detecting available features...
FEATURES=""
if command -v gh > /dev/null; then
FEATURES="$FEATURES github"
fi
if command -v docker > /dev/null; then
FEATURES="$FEATURES docker"
fi
Available features: $FEATURES
if echo "$FEATURES" | grep -q "github"; then
# Full functionality with GitHub integration
echo "✓ GitHub integration available"
else
# Reduced functionality without GitHub
echo "⚠ Limited functionality: GitHub CLI not installed"
echo " Install 'gh' for full features"
fi
[Adapt behavior based on available features...]
```
## User Experience for Unknown Users
### Clear Onboarding
**First-run experience:**
```markdown
---
description: Command with onboarding
allowed-tools: Read, Write
---
# First Run Check
if [ ! -f ".claude/command-initialized" ]; then
**Welcome to Command Name!**
This appears to be your first time using this command.
WHAT THIS COMMAND DOES:
[Brief explanation of purpose and benefits]
QUICK START:
1. Basic usage: /command [arg]
2. For help: /command help
3. Examples: /command examples
SETUP:
No additional setup required. You're ready to go!
✓ Initialization complete
[Create initialization marker]
Ready to proceed with your request...
fi
[Normal command execution...]
```
**Progressive feature discovery:**
```markdown
---
description: Command with tips
---
# Command Execution
[Main functionality...]
---
💡 TIP: Did you know?
You can speed up this command with the --fast flag:
/command --fast [args]
For more tips: /command tips
```
### Comprehensive Error Handling
**Anticipate user mistakes:**
```markdown
---
description: Forgiving command
---
# User Input Handling
Argument: "$1"
<!-- Check for common typos -->
if [ "$1" = "hlep" ] || [ "$1" = "hepl" ]; then
Did you mean: help?
Showing help instead...
[Display help]
Exit.
fi
<!-- Suggest similar commands if not found -->
if [ "$1" != "valid-option1" ] && [ "$1" != "valid-option2" ]; then
❌ Unknown option: $1
Did you mean:
- valid-option1 (most similar)
- valid-option2
For all options: /command help
Exit.
fi
[Command continues...]
```
**Helpful diagnostics:**
```markdown
---
description: Diagnostic command
---
# Operation Failed
The operation could not complete.
**Diagnostic Information:**
Environment:
- Platform: $(uname)
- Shell: $SHELL
- Working directory: $(pwd)
- Command: /command $@
Checking common issues:
- Git repository: $(git rev-parse --git-dir 2>&1)
- Write permissions: $(test -w . && echo "OK" || echo "DENIED")
- Required files: $(test -f config.yml && echo "Found" || echo "Missing")
This information helps debug the issue.
For support, include the above diagnostics.
```
## Distribution Best Practices
### Namespace Awareness
**Avoid name collisions:**
```markdown
---
description: Namespaced command
---
<!--
COMMAND NAME: plugin-name-command
This command is namespaced with the plugin name to avoid
conflicts with commands from other plugins.
Alternative naming approaches:
- Use plugin prefix: /plugin-command
- Use category: /category-command
- Use verb-noun: /verb-noun
Chosen approach: plugin-name prefix
Reasoning: Clearest ownership, least likely to conflict
-->
# Plugin Name Command
[Implementation...]
```
**Document naming rationale:**
```markdown
<!--
NAMING DECISION:
Command name: /deploy-app
Alternatives considered:
- /deploy: Too generic, likely conflicts
- /app-deploy: Less intuitive ordering
- /my-plugin-deploy: Too verbose
Final choice balances:
- Discoverability (clear purpose)
- Brevity (easy to type)
- Uniqueness (unlikely conflicts)
-->
```
### Configurability
**User preferences:**
```markdown
---
description: Configurable command
allowed-tools: Read
---
# Load User Configuration
Default configuration:
- verbose: false
- color: true
- max_results: 10
Checking for user config: .claude/plugin-name.local.md
if [ -f ".claude/plugin-name.local.md" ]; then
# Parse YAML frontmatter for settings
VERBOSE=$(grep "^verbose:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ')
COLOR=$(grep "^color:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ')
MAX_RESULTS=$(grep "^max_results:" .claude/plugin-name.local.md | cut -d: -f2 | tr -d ' ')
echo "✓ Using user configuration"
else
echo "Using default configuration"
echo "Create .claude/plugin-name.local.md to customize"
fi
[Use configuration in command...]
```
**Sensible defaults:**
```markdown
---
description: Command with smart defaults
---
# Smart Defaults
Configuration:
- Format: ${FORMAT:-json} # Defaults to json
- Output: ${OUTPUT:-stdout} # Defaults to stdout
- Verbose: ${VERBOSE:-false} # Defaults to false
These defaults work for 80% of use cases.
Override with arguments:
/command --format yaml --output file.txt --verbose
Or set in .claude/plugin-name.local.md:
\`\`\`yaml
---
format: yaml
output: custom.txt
verbose: true
---
\`\`\`
```
### Version Compatibility
**Version checking:**
```markdown
---
description: Version-aware command
---
<!--
COMMAND VERSION: 2.1.0
COMPATIBILITY:
- Requires plugin version: >= 2.0.0
- Breaking changes from v1.x documented in MIGRATION.md
VERSION HISTORY:
- v2.1.0: Added --new-feature flag
- v2.0.0: BREAKING: Changed argument order
- v1.0.0: Initial release
-->
# Version Check
Command version: 2.1.0
Plugin version: [detect from plugin.json]
if [ "$PLUGIN_VERSION" < "2.0.0" ]; then
❌ ERROR: Incompatible plugin version
This command requires plugin version >= 2.0.0
Current version: $PLUGIN_VERSION
Update plugin:
/plugin update plugin-name
Exit.
fi
✓ Version compatible
[Command continues...]
```
**Deprecation warnings:**
```markdown
---
description: Command with deprecation warnings
---
# Deprecation Check
if [ "$1" = "--old-flag" ]; then
⚠️ DEPRECATION WARNING
The --old-flag option is deprecated as of v2.0.0
It will be removed in v3.0.0 (est. June 2025)
Use instead: --new-flag
Example:
Old: /command --old-flag value
New: /command --new-flag value
See migration guide: /command migrate
Continuing with deprecated behavior for now...
fi
[Handle both old and new flags during deprecation period...]
```
## Marketplace Presentation
### Command Discovery
**Descriptive naming:**
```markdown
---
description: Review pull request with security and quality checks
---
<!-- GOOD: Descriptive name and description -->
```
```markdown
---
description: Do the thing
---
<!-- BAD: Vague description -->
```
**Searchable keywords:**
```markdown
<!--
KEYWORDS: security, code-review, quality, validation, audit
These keywords help users discover this command when searching
for related functionality in the marketplace.
-->
```
### Showcase Examples
**Compelling demonstrations:**
```markdown
---
description: Advanced code analysis command
---
# Code Analysis Command
This command performs deep code analysis with actionable insights.
## Demo: Quick Security Audit
Try it now:
\`\`\`
/analyze-code src/ --security
\`\`\`
**What you'll get:**
- Security vulnerability detection
- Code quality metrics
- Performance bottleneck identification
- Actionable recommendations
**Sample output:**
\`\`\`
Security Analysis Results
=========================
🔴 Critical (2):
- SQL injection risk in users.js:45
- XSS vulnerability in display.js:23
🟡 Warnings (5):
- Unvalidated input in api.js:67
...
Recommendations:
1. Fix critical issues immediately
2. Review warnings before next release
3. Run /analyze-code --fix for auto-fixes
\`\`\`
---
Ready to analyze your code...
[Command implementation...]
```
### User Reviews and Feedback
**Feedback mechanism:**
```markdown
---
description: Command with feedback
---
# Command Complete
[Command results...]
---
**How was your experience?**
This helps improve the command for everyone.
Rate this command:
- 👍 Helpful
- 👎 Not helpful
- 🐛 Found a bug
- 💡 Have a suggestion
Reply with an emoji or:
- /command feedback
Your feedback matters!
```
**Usage analytics preparation:**
```markdown
<!--
ANALYTICS NOTES:
Track for improvement:
- Most common arguments
- Failure rates
- Average execution time
- User satisfaction scores
Privacy-preserving:
- No personally identifiable information
- Aggregate statistics only
- User opt-out respected
-->
```
## Quality Standards
### Professional Polish
**Consistent branding:**
```markdown
---
description: Branded command
---
# ✨ Command Name
Part of the [Plugin Name] suite
[Command functionality...]
---
**Need Help?**
- Documentation: https://docs.example.com
- Support: support@example.com
- Community: https://community.example.com
Powered by Plugin Name v2.1.0
```
**Attention to detail:**
```markdown
<!-- Details that matter -->
✓ Use proper emoji/symbols consistently
✓ Align output columns neatly
✓ Format numbers with thousands separators
✓ Use color/formatting appropriately
✓ Provide progress indicators
✓ Show estimated time remaining
✓ Confirm successful operations
```
### Reliability
**Idempotency:**
```markdown
---
description: Idempotent command
---
# Safe Repeated Execution
Checking if operation already completed...
if [ -f ".claude/operation-completed.flag" ]; then
Operation already completed
Completed at: $(cat .claude/operation-completed.flag)
To re-run:
1. Remove flag: rm .claude/operation-completed.flag
2. Run command again
Otherwise, no action needed.
Exit.
fi
Performing operation...
[Safe, repeatable operation...]
Marking complete...
echo "$(date)" > .claude/operation-completed.flag
```
**Atomic operations:**
```markdown
---
description: Atomic command
---
# Atomic Operation
This operation is atomic - either fully succeeds or fully fails.
Creating temporary workspace...
TEMP_DIR=$(mktemp -d)
Performing changes in isolated environment...
[Make changes in $TEMP_DIR]
if [ $? -eq 0 ]; then
✓ Changes validated
Applying changes atomically...
mv $TEMP_DIR/* ./target/
✓ Operation complete
else
❌ Changes failed validation
Rolling back...
rm -rf $TEMP_DIR
No changes applied. Safe to retry.
fi
```
## Testing for Distribution
### Pre-Release Checklist
```markdown
<!--
PRE-RELEASE CHECKLIST:
Functionality:
- [ ] Works on macOS
- [ ] Works on Linux
- [ ] Works on Windows (WSL)
- [ ] All arguments tested
- [ ] Error cases handled
- [ ] Edge cases covered
User Experience:
- [ ] Clear description
- [ ] Helpful error messages
- [ ] Examples provided
- [ ] First-run experience good
- [ ] Documentation complete
Distribution:
- [ ] No hardcoded paths
- [ ] Dependencies documented
- [ ] Configuration options clear
- [ ] Version number set
- [ ] Changelog updated
Quality:
- [ ] No TODO comments
- [ ] No debug code
- [ ] Performance acceptable
- [ ] Security reviewed
- [ ] Privacy considered
Support:
- [ ] README complete
- [ ] Troubleshooting guide
- [ ] Support contact provided
- [ ] Feedback mechanism
- [ ] License specified
-->
```
### Beta Testing
**Beta release approach:**
```markdown
---
description: Beta command (v0.9.0)
---
# 🧪 Beta Command
**This is a beta release**
Features may change based on feedback.
BETA STATUS:
- Version: 0.9.0
- Stability: Experimental
- Support: Limited
- Feedback: Encouraged
Known limitations:
- Performance not optimized
- Some edge cases not handled
- Documentation incomplete
Help improve this command:
- Report issues: /command report-issue
- Suggest features: /command suggest
- Join beta testers: /command join-beta
---
[Command implementation...]
---
**Thank you for beta testing!**
Your feedback helps make this command better.
```
## Maintenance and Updates
### Update Strategy
**Versioned commands:**
```markdown
<!--
VERSION STRATEGY:
Major (X.0.0): Breaking changes
- Document all breaking changes
- Provide migration guide
- Support old version briefly
Minor (x.Y.0): New features
- Backward compatible
- Announce new features
- Update examples
Patch (x.y.Z): Bug fixes
- No user-facing changes
- Update changelog
- Security fixes prioritized
Release schedule:
- Patches: As needed
- Minors: Monthly
- Majors: Annually or as needed
-->
```
**Update notifications:**
```markdown
---
description: Update-aware command
---
# Check for Updates
Current version: 2.1.0
Latest version: [check if available]
if [ "$CURRENT_VERSION" != "$LATEST_VERSION" ]; then
📢 UPDATE AVAILABLE
New version: $LATEST_VERSION
Current: $CURRENT_VERSION
What's new:
- Feature improvements
- Bug fixes
- Performance enhancements
Update with:
/plugin update plugin-name
Release notes: https://releases.example.com/v$LATEST_VERSION
fi
[Command continues...]
```
## Best Practices Summary
### Distribution Design
1. **Universal**: Works across platforms and environments
2. **Self-contained**: Minimal dependencies, clear requirements
3. **Graceful**: Degrades gracefully when features unavailable
4. **Forgiving**: Anticipates and handles user mistakes
5. **Helpful**: Clear errors, good defaults, excellent docs
### Marketplace Success
1. **Discoverable**: Clear name, good description, searchable keywords
2. **Professional**: Polished presentation, consistent branding
3. **Reliable**: Tested thoroughly, handles edge cases
4. **Maintainable**: Versioned, updated regularly, supported
5. **User-focused**: Great UX, responsive to feedback
### Quality Standards
1. **Complete**: Fully documented, all features working
2. **Tested**: Works in real environments, edge cases handled
3. **Secure**: No vulnerabilities, safe operations
4. **Performant**: Reasonable speed, resource-efficient
5. **Ethical**: Privacy-respecting, user consent
With these considerations, commands become marketplace-ready and delight users across diverse environments and use cases.

View File

@@ -0,0 +1,609 @@
# Plugin-Specific Command Features Reference
This reference covers features and patterns specific to commands bundled in Claude Code plugins.
## Table of Contents
- [Plugin Command Discovery](#plugin-command-discovery)
- [CLAUDE_PLUGIN_ROOT Environment Variable](#claude_plugin_root-environment-variable)
- [Plugin Command Patterns](#plugin-command-patterns)
- [Integration with Plugin Components](#integration-with-plugin-components)
- [Validation Patterns](#validation-patterns)
## Plugin Command Discovery
### Auto-Discovery
Claude Code automatically discovers commands in plugins using the following locations:
```
plugin-name/
├── commands/ # Auto-discovered commands
│ ├── foo.md # /foo (plugin:plugin-name)
│ └── bar.md # /bar (plugin:plugin-name)
└── plugin.json # Plugin manifest
```
**Key points:**
- Commands are discovered at plugin load time
- No manual registration required
- Commands appear in `/help` with "(plugin:plugin-name)" label
- Subdirectories create namespaces
### Namespaced Plugin Commands
Organize commands in subdirectories for logical grouping:
```
plugin-name/
└── commands/
├── review/
│ ├── security.md # /security (plugin:plugin-name:review)
│ └── style.md # /style (plugin:plugin-name:review)
└── deploy/
├── staging.md # /staging (plugin:plugin-name:deploy)
└── prod.md # /prod (plugin:plugin-name:deploy)
```
**Namespace behavior:**
- Subdirectory name becomes namespace
- Shown as "(plugin:plugin-name:namespace)" in `/help`
- Helps organize related commands
- Use when plugin has 5+ commands
### Command Naming Conventions
**Plugin command names should:**
1. Be descriptive and action-oriented
2. Avoid conflicts with common command names
3. Use hyphens for multi-word names
4. Consider prefixing with plugin name for uniqueness
**Examples:**
```
Good:
- /mylyn-sync (plugin-specific prefix)
- /analyze-performance (descriptive action)
- /docker-compose-up (clear purpose)
Avoid:
- /test (conflicts with common name)
- /run (too generic)
- /do-stuff (not descriptive)
```
## CLAUDE_PLUGIN_ROOT Environment Variable
### Purpose
`${CLAUDE_PLUGIN_ROOT}` is a special environment variable available in plugin commands that resolves to the absolute path of the plugin directory.
**Why it matters:**
- Enables portable paths within plugin
- Allows referencing plugin files and scripts
- Works across different installations
- Essential for multi-file plugin operations
### Basic Usage
Reference files within your plugin:
```markdown
---
description: Analyze using plugin script
allowed-tools: Bash(node:*), Read
---
Run analysis: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/analyze.js`
Read template: @${CLAUDE_PLUGIN_ROOT}/templates/report.md
```
**Expands to:**
```
Run analysis: !`node /path/to/plugins/plugin-name/scripts/analyze.js`
Read template: @/path/to/plugins/plugin-name/templates/report.md
```
### Common Patterns
#### 1. Executing Plugin Scripts
```markdown
---
description: Run custom linter from plugin
allowed-tools: Bash(node:*)
---
Lint results: !`node ${CLAUDE_PLUGIN_ROOT}/bin/lint.js $1`
Review the linting output and suggest fixes.
```
#### 2. Loading Configuration Files
```markdown
---
description: Deploy using plugin configuration
allowed-tools: Read, Bash(*)
---
Configuration: @${CLAUDE_PLUGIN_ROOT}/config/deploy-config.json
Deploy application using the configuration above for $1 environment.
```
#### 3. Accessing Plugin Resources
```markdown
---
description: Generate report from template
---
Use this template: @${CLAUDE_PLUGIN_ROOT}/templates/api-report.md
Generate a report for @$1 following the template format.
```
#### 4. Multi-Step Plugin Workflows
```markdown
---
description: Complete plugin workflow
allowed-tools: Bash(*), Read
---
Step 1 - Prepare: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/prepare.sh $1`
Step 2 - Config: @${CLAUDE_PLUGIN_ROOT}/config/$1.json
Step 3 - Execute: !`${CLAUDE_PLUGIN_ROOT}/bin/execute $1`
Review results and report status.
```
### Best Practices
1. **Always use for plugin-internal paths:**
```markdown
# Good
@${CLAUDE_PLUGIN_ROOT}/templates/foo.md
# Bad
@./templates/foo.md # Relative to current directory, not plugin
```
2. **Validate file existence:**
```markdown
---
description: Use plugin config if exists
allowed-tools: Bash(test:*), Read
---
!`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "exists" || echo "missing"`
If config exists, load it: @${CLAUDE_PLUGIN_ROOT}/config.json
Otherwise, use defaults...
```
3. **Document plugin file structure:**
```markdown
<!--
Plugin structure:
${CLAUDE_PLUGIN_ROOT}/
├── scripts/analyze.js (analysis script)
├── templates/ (report templates)
└── config/ (configuration files)
-->
```
4. **Combine with arguments:**
```markdown
Run: !`${CLAUDE_PLUGIN_ROOT}/bin/process.sh $1 $2`
```
### Troubleshooting
**Variable not expanding:**
- Ensure command is loaded from plugin
- Check bash execution is allowed
- Verify syntax is exact: `${CLAUDE_PLUGIN_ROOT}`
**File not found errors:**
- Verify file exists in plugin directory
- Check file path is correct relative to plugin root
- Ensure file permissions allow reading/execution
**Path with spaces:**
- Bash commands automatically handle spaces
- File references work with spaces in paths
- No special quoting needed
## Plugin Command Patterns
### Pattern 1: Configuration-Based Commands
Commands that load plugin-specific configuration:
```markdown
---
description: Deploy using plugin settings
allowed-tools: Read, Bash(*)
---
Load configuration: @${CLAUDE_PLUGIN_ROOT}/deploy-config.json
Deploy to $1 environment using:
1. Configuration settings above
2. Current git branch: !`git branch --show-current`
3. Application version: !`cat package.json | grep version`
Execute deployment and monitor progress.
```
**When to use:** Commands that need consistent settings across invocations
### Pattern 2: Template-Based Generation
Commands that use plugin templates:
```markdown
---
description: Generate documentation from template
argument-hint: [component-name]
---
Template: @${CLAUDE_PLUGIN_ROOT}/templates/component-docs.md
Generate documentation for $1 component following the template structure.
Include:
- Component purpose and usage
- API reference
- Examples
- Testing guidelines
```
**When to use:** Standardized output generation
### Pattern 3: Multi-Script Workflow
Commands that orchestrate multiple plugin scripts:
```markdown
---
description: Complete build and test workflow
allowed-tools: Bash(*)
---
Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh`
Validate: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh`
Test: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/test.sh`
Review all outputs and report:
1. Build status
2. Validation results
3. Test results
4. Recommended next steps
```
**When to use:** Complex plugin workflows with multiple steps
### Pattern 4: Environment-Aware Commands
Commands that adapt to environment:
```markdown
---
description: Deploy based on environment
argument-hint: [dev|staging|prod]
---
Environment config: @${CLAUDE_PLUGIN_ROOT}/config/$1.json
Environment check: !`echo "Deploying to: $1"`
Deploy application using $1 environment configuration.
Verify deployment and run smoke tests.
```
**When to use:** Commands that behave differently per environment
### Pattern 5: Plugin Data Management
Commands that manage plugin-specific data:
```markdown
---
description: Save analysis results to plugin cache
allowed-tools: Bash(*), Read, Write
---
Cache directory: ${CLAUDE_PLUGIN_ROOT}/cache/
Analyze @$1 and save results to cache:
!`mkdir -p ${CLAUDE_PLUGIN_ROOT}/cache && date > ${CLAUDE_PLUGIN_ROOT}/cache/last-run.txt`
Store analysis for future reference and comparison.
```
**When to use:** Commands that need persistent data storage
## Integration with Plugin Components
### Invoking Plugin Agents
Commands can trigger plugin agents using the Task tool:
```markdown
---
description: Deep analysis using plugin agent
argument-hint: [file-path]
---
Initiate deep code analysis of @$1 using the code-analyzer agent.
The agent will:
1. Analyze code structure
2. Identify patterns
3. Suggest improvements
4. Generate detailed report
Note: This uses the Task tool to launch the plugin's code-analyzer agent.
```
**Key points:**
- Agent must be defined in plugin's `agents/` directory
- Claude will automatically use Task tool to launch agent
- Agent has access to same plugin resources
### Invoking Plugin Skills
Commands can reference plugin skills for specialized knowledge:
```markdown
---
description: API documentation with best practices
argument-hint: [api-file]
---
Document the API in @$1 following our API documentation standards.
Use the api-docs-standards skill to ensure documentation includes:
- Endpoint descriptions
- Parameter specifications
- Response formats
- Error codes
- Usage examples
Note: This leverages the plugin's api-docs-standards skill for consistency.
```
**Key points:**
- Skill must be defined in plugin's `skills/` directory
- Mention skill by name to hint Claude should invoke it
- Skills provide specialized domain knowledge
### Coordinating with Plugin Hooks
Commands can be designed to work with plugin hooks:
```markdown
---
description: Commit with pre-commit validation
allowed-tools: Bash(git:*)
---
Stage changes: !\`git add $1\`
Commit changes: !\`git commit -m "$2"\`
Note: This commit will trigger the plugin's pre-commit hook for validation.
Review hook output for any issues.
```
**Key points:**
- Hooks execute automatically on events
- Commands can prepare state for hooks
- Document hook interaction in command
### Multi-Component Plugin Commands
Commands that coordinate multiple plugin components:
```markdown
---
description: Comprehensive code review workflow
argument-hint: [file-path]
---
File to review: @$1
Execute comprehensive review:
1. **Static Analysis** (via plugin scripts)
!`node ${CLAUDE_PLUGIN_ROOT}/scripts/lint.js $1`
2. **Deep Review** (via plugin agent)
Launch the code-reviewer agent for detailed analysis.
3. **Best Practices** (via plugin skill)
Use the code-standards skill to ensure compliance.
4. **Documentation** (via plugin template)
Template: @${CLAUDE_PLUGIN_ROOT}/templates/review-report.md
Generate final report combining all outputs.
```
**When to use:** Complex workflows leveraging multiple plugin capabilities
## Validation Patterns
### Input Validation
Commands should validate inputs before processing:
```markdown
---
description: Deploy to environment with validation
argument-hint: [environment]
---
Validate environment: !`echo "$1" | grep -E "^(dev|staging|prod)$" || echo "INVALID"`
$IF($1 in [dev, staging, prod],
Deploy to $1 environment using validated configuration,
ERROR: Invalid environment '$1'. Must be one of: dev, staging, prod
)
```
**Validation approaches:**
1. Bash validation using grep/test
2. Inline validation in prompt
3. Script-based validation
### File Existence Checks
Verify required files exist:
```markdown
---
description: Process configuration file
argument-hint: [config-file]
---
Check file: !`test -f $1 && echo "EXISTS" || echo "MISSING"`
Process configuration if file exists: @$1
If file doesn't exist, explain:
- Expected location
- Required format
- How to create it
```
### Required Arguments
Validate required arguments provided:
```markdown
---
description: Create deployment with version
argument-hint: [environment] [version]
---
Validate inputs: !`test -n "$1" -a -n "$2" && echo "OK" || echo "MISSING"`
$IF($1 AND $2,
Deploy version $2 to $1 environment,
ERROR: Both environment and version required. Usage: /deploy [env] [version]
)
```
### Plugin Resource Validation
Verify plugin resources available:
```markdown
---
description: Run analysis with plugin tools
allowed-tools: Bash(test:*)
---
Validate plugin setup:
- Config exists: !`test -f ${CLAUDE_PLUGIN_ROOT}/config.json && echo "✓" || echo "✗"`
- Scripts exist: !`test -d ${CLAUDE_PLUGIN_ROOT}/scripts && echo "✓" || echo "✗"`
- Tools available: !`test -x ${CLAUDE_PLUGIN_ROOT}/bin/analyze && echo "✓" || echo "✗"`
If all checks pass, proceed with analysis.
Otherwise, report missing components and installation steps.
```
### Output Validation
Validate command execution results:
```markdown
---
description: Build and validate output
allowed-tools: Bash(*)
---
Build: !`bash ${CLAUDE_PLUGIN_ROOT}/scripts/build.sh`
Validate output:
- Exit code: !`echo $?`
- Output exists: !`test -d dist && echo "✓" || echo "✗"`
- File count: !`find dist -type f | wc -l`
Report build status and any validation failures.
```
### Graceful Error Handling
Handle errors gracefully with helpful messages:
```markdown
---
description: Process file with error handling
argument-hint: [file-path]
---
Try processing: !`node ${CLAUDE_PLUGIN_ROOT}/scripts/process.js $1 2>&1 || echo "ERROR: $?"`
If processing succeeded:
- Report results
- Suggest next steps
If processing failed:
- Explain likely causes
- Provide troubleshooting steps
- Suggest alternative approaches
```
## Best Practices Summary
### Plugin Commands Should:
1. **Use ${CLAUDE_PLUGIN_ROOT} for all plugin-internal paths**
- Scripts, templates, configuration, resources
2. **Validate inputs early**
- Check required arguments
- Verify file existence
- Validate argument formats
3. **Document plugin structure**
- Explain required files
- Document script purposes
- Clarify dependencies
4. **Integrate with plugin components**
- Reference agents for complex tasks
- Use skills for specialized knowledge
- Coordinate with hooks when relevant
5. **Provide helpful error messages**
- Explain what went wrong
- Suggest how to fix
- Offer alternatives
6. **Handle edge cases**
- Missing files
- Invalid arguments
- Failed script execution
- Missing dependencies
7. **Keep commands focused**
- One clear purpose per command
- Delegate complex logic to scripts
- Use agents for multi-step workflows
8. **Test across installations**
- Verify paths work everywhere
- Test with different arguments
- Validate error cases
---
For general command development, see main SKILL.md.
For command examples, see examples/ directory.

View File

@@ -0,0 +1,702 @@
# Command Testing Strategies
Comprehensive strategies for testing slash commands before deployment and distribution.
## Overview
Testing commands ensures they work correctly, handle edge cases, and provide good user experience. A systematic testing approach catches issues early and builds confidence in command reliability.
## Testing Levels
### Level 1: Syntax and Structure Validation
**What to test:**
- YAML frontmatter syntax
- Markdown format
- File location and naming
**How to test:**
```bash
# Validate YAML frontmatter
head -n 20 .claude/commands/my-command.md | grep -A 10 "^---"
# Check for closing frontmatter marker
head -n 20 .claude/commands/my-command.md | grep -c "^---" # Should be 2
# Verify file has .md extension
ls .claude/commands/*.md
# Check file is in correct location
test -f .claude/commands/my-command.md && echo "Found" || echo "Missing"
```
**Automated validation script:**
```bash
#!/bin/bash
# validate-command.sh
COMMAND_FILE="$1"
if [ ! -f "$COMMAND_FILE" ]; then
echo "ERROR: File not found: $COMMAND_FILE"
exit 1
fi
# Check .md extension
if [[ ! "$COMMAND_FILE" =~ \.md$ ]]; then
echo "ERROR: File must have .md extension"
exit 1
fi
# Validate YAML frontmatter if present
if head -n 1 "$COMMAND_FILE" | grep -q "^---"; then
# Count frontmatter markers
MARKERS=$(head -n 50 "$COMMAND_FILE" | grep -c "^---")
if [ "$MARKERS" -ne 2 ]; then
echo "ERROR: Invalid YAML frontmatter (need exactly 2 '---' markers)"
exit 1
fi
echo "✓ YAML frontmatter syntax valid"
fi
# Check for empty file
if [ ! -s "$COMMAND_FILE" ]; then
echo "ERROR: File is empty"
exit 1
fi
echo "✓ Command file structure valid"
```
### Level 2: Frontmatter Field Validation
**What to test:**
- Field types correct
- Values in valid ranges
- Required fields present (if any)
**Validation script:**
```bash
#!/bin/bash
# validate-frontmatter.sh
COMMAND_FILE="$1"
# Extract YAML frontmatter
FRONTMATTER=$(sed -n '/^---$/,/^---$/p' "$COMMAND_FILE" | sed '1d;$d')
if [ -z "$FRONTMATTER" ]; then
echo "No frontmatter to validate"
exit 0
fi
# Check 'model' field if present
if echo "$FRONTMATTER" | grep -q "^model:"; then
MODEL=$(echo "$FRONTMATTER" | grep "^model:" | cut -d: -f2 | tr -d ' ')
if ! echo "sonnet opus haiku" | grep -qw "$MODEL"; then
echo "ERROR: Invalid model '$MODEL' (must be sonnet, opus, or haiku)"
exit 1
fi
echo "✓ Model field valid: $MODEL"
fi
# Check 'allowed-tools' field format
if echo "$FRONTMATTER" | grep -q "^allowed-tools:"; then
echo "✓ allowed-tools field present"
# Could add more sophisticated validation here
fi
# Check 'description' length
if echo "$FRONTMATTER" | grep -q "^description:"; then
DESC=$(echo "$FRONTMATTER" | grep "^description:" | cut -d: -f2-)
LENGTH=${#DESC}
if [ "$LENGTH" -gt 80 ]; then
echo "WARNING: Description length $LENGTH (recommend < 60 chars)"
else
echo "✓ Description length acceptable: $LENGTH chars"
fi
fi
echo "✓ Frontmatter fields valid"
```
### Level 3: Manual Command Invocation
**What to test:**
- Command appears in `/help`
- Command executes without errors
- Output is as expected
**Test procedure:**
```bash
# 1. Start Claude Code
claude --debug
# 2. Check command appears in help
> /help
# Look for your command in the list
# 3. Invoke command without arguments
> /my-command
# Check for reasonable error or behavior
# 4. Invoke with valid arguments
> /my-command arg1 arg2
# Verify expected behavior
# 5. Check debug logs
tail -f ~/.claude/debug-logs/latest
# Look for errors or warnings
```
### Level 4: Argument Testing
**What to test:**
- Positional arguments work ($1, $2, etc.)
- $ARGUMENTS captures all arguments
- Missing arguments handled gracefully
- Invalid arguments detected
**Test matrix:**
| Test Case | Command | Expected Result |
|-----------|---------|-----------------|
| No args | `/cmd` | Graceful handling or useful message |
| One arg | `/cmd arg1` | $1 substituted correctly |
| Two args | `/cmd arg1 arg2` | $1 and $2 substituted |
| Extra args | `/cmd a b c d` | All captured or extras ignored appropriately |
| Special chars | `/cmd "arg with spaces"` | Quotes handled correctly |
| Empty arg | `/cmd ""` | Empty string handled |
**Test script:**
```bash
#!/bin/bash
# test-command-arguments.sh
COMMAND="$1"
echo "Testing argument handling for /$COMMAND"
echo
echo "Test 1: No arguments"
echo " Command: /$COMMAND"
echo " Expected: [describe expected behavior]"
echo " Manual test required"
echo
echo "Test 2: Single argument"
echo " Command: /$COMMAND test-value"
echo " Expected: 'test-value' appears in output"
echo " Manual test required"
echo
echo "Test 3: Multiple arguments"
echo " Command: /$COMMAND arg1 arg2 arg3"
echo " Expected: All arguments used appropriately"
echo " Manual test required"
echo
echo "Test 4: Special characters"
echo " Command: /$COMMAND \"value with spaces\""
echo " Expected: Entire phrase captured"
echo " Manual test required"
```
### Level 5: File Reference Testing
**What to test:**
- @ syntax loads file contents
- Non-existent files handled
- Large files handled appropriately
- Multiple file references work
**Test procedure:**
```bash
# Create test files
echo "Test content" > /tmp/test-file.txt
echo "Second file" > /tmp/test-file-2.txt
# Test single file reference
> /my-command /tmp/test-file.txt
# Verify file content is read
# Test non-existent file
> /my-command /tmp/nonexistent.txt
# Verify graceful error handling
# Test multiple files
> /my-command /tmp/test-file.txt /tmp/test-file-2.txt
# Verify both files processed
# Test large file
dd if=/dev/zero of=/tmp/large-file.bin bs=1M count=100
> /my-command /tmp/large-file.bin
# Verify reasonable behavior (may truncate or warn)
# Cleanup
rm /tmp/test-file*.txt /tmp/large-file.bin
```
### Level 6: Bash Execution Testing
**What to test:**
- !` commands execute correctly
- Command output included in prompt
- Command failures handled
- Security: only allowed commands run
**Test procedure:**
```bash
# Create test command with bash execution
cat > .claude/commands/test-bash.md << 'EOF'
---
description: Test bash execution
allowed-tools: Bash(echo:*), Bash(date:*)
---
Current date: !`date`
Test output: !`echo "Hello from bash"`
Analysis of output above...
EOF
# Test in Claude Code
> /test-bash
# Verify:
# 1. Date appears correctly
# 2. Echo output appears
# 3. No errors in debug logs
# Test with disallowed command (should fail or be blocked)
cat > .claude/commands/test-forbidden.md << 'EOF'
---
description: Test forbidden command
allowed-tools: Bash(echo:*)
---
Trying forbidden: !`ls -la /`
EOF
> /test-forbidden
# Verify: Permission denied or appropriate error
```
### Level 7: Integration Testing
**What to test:**
- Commands work with other plugin components
- Commands interact correctly with each other
- State management works across invocations
- Workflow commands execute in sequence
**Test scenarios:**
**Scenario 1: Command + Hook Integration**
```bash
# Setup: Command that triggers a hook
# Test: Invoke command, verify hook executes
# Command: .claude/commands/risky-operation.md
# Hook: PreToolUse that validates the operation
> /risky-operation
# Verify: Hook executes and validates before command completes
```
**Scenario 2: Command Sequence**
```bash
# Setup: Multi-command workflow
> /workflow-init
# Verify: State file created
> /workflow-step2
# Verify: State file read, step 2 executes
> /workflow-complete
# Verify: State file cleaned up
```
**Scenario 3: Command + MCP Integration**
```bash
# Setup: Command uses MCP tools
# Test: Verify MCP server accessible
> /mcp-command
# Verify:
# 1. MCP server starts (if stdio)
# 2. Tool calls succeed
# 3. Results included in output
```
## Automated Testing Approaches
### Command Test Suite
Create a test suite script:
```bash
#!/bin/bash
# test-commands.sh - Command test suite
TEST_DIR=".claude/commands"
FAILED_TESTS=0
echo "Command Test Suite"
echo "=================="
echo
for cmd_file in "$TEST_DIR"/*.md; do
cmd_name=$(basename "$cmd_file" .md)
echo "Testing: $cmd_name"
# Validate structure
if ./validate-command.sh "$cmd_file"; then
echo " ✓ Structure valid"
else
echo " ✗ Structure invalid"
((FAILED_TESTS++))
fi
# Validate frontmatter
if ./validate-frontmatter.sh "$cmd_file"; then
echo " ✓ Frontmatter valid"
else
echo " ✗ Frontmatter invalid"
((FAILED_TESTS++))
fi
echo
done
echo "=================="
echo "Tests complete"
echo "Failed: $FAILED_TESTS"
exit $FAILED_TESTS
```
### Pre-Commit Hook
Validate commands before committing:
```bash
#!/bin/bash
# .git/hooks/pre-commit
echo "Validating commands..."
COMMANDS_CHANGED=$(git diff --cached --name-only | grep "\.claude/commands/.*\.md")
if [ -z "$COMMANDS_CHANGED" ]; then
echo "No commands changed"
exit 0
fi
for cmd in $COMMANDS_CHANGED; do
echo "Checking: $cmd"
if ! ./scripts/validate-command.sh "$cmd"; then
echo "ERROR: Command validation failed: $cmd"
exit 1
fi
done
echo "✓ All commands valid"
```
### Continuous Testing
Test commands in CI/CD:
```yaml
# .github/workflows/test-commands.yml
name: Test Commands
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Validate command structure
run: |
for cmd in .claude/commands/*.md; do
echo "Testing: $cmd"
./scripts/validate-command.sh "$cmd"
done
- name: Validate frontmatter
run: |
for cmd in .claude/commands/*.md; do
./scripts/validate-frontmatter.sh "$cmd"
done
- name: Check for TODOs
run: |
if grep -r "TODO" .claude/commands/; then
echo "ERROR: TODOs found in commands"
exit 1
fi
```
## Edge Case Testing
### Test Edge Cases
**Empty arguments:**
```bash
> /cmd ""
> /cmd '' ''
```
**Special characters:**
```bash
> /cmd "arg with spaces"
> /cmd arg-with-dashes
> /cmd arg_with_underscores
> /cmd arg/with/slashes
> /cmd 'arg with "quotes"'
```
**Long arguments:**
```bash
> /cmd $(python -c "print('a' * 10000)")
```
**Unusual file paths:**
```bash
> /cmd ./file
> /cmd ../file
> /cmd ~/file
> /cmd "/path with spaces/file"
```
**Bash command edge cases:**
```markdown
# Commands that might fail
!`exit 1`
!`false`
!`command-that-does-not-exist`
# Commands with special output
!`echo ""`
!`cat /dev/null`
!`yes | head -n 1000000`
```
## Performance Testing
### Response Time Testing
```bash
#!/bin/bash
# test-command-performance.sh
COMMAND="$1"
echo "Testing performance of /$COMMAND"
echo
for i in {1..5}; do
echo "Run $i:"
START=$(date +%s%N)
# Invoke command (manual step - record time)
echo " Invoke: /$COMMAND"
echo " Start time: $START"
echo " (Record end time manually)"
echo
done
echo "Analyze results:"
echo " - Average response time"
echo " - Variance"
echo " - Acceptable threshold: < 3 seconds for fast commands"
```
### Resource Usage Testing
```bash
# Monitor Claude Code during command execution
# In terminal 1:
claude --debug
# In terminal 2:
watch -n 1 'ps aux | grep claude'
# Execute command and observe:
# - Memory usage
# - CPU usage
# - Process count
```
## User Experience Testing
### Usability Checklist
- [ ] Command name is intuitive
- [ ] Description is clear in `/help`
- [ ] Arguments are well-documented
- [ ] Error messages are helpful
- [ ] Output is formatted readably
- [ ] Long-running commands show progress
- [ ] Results are actionable
- [ ] Edge cases have good UX
### User Acceptance Testing
Recruit testers:
```markdown
# Testing Guide for Beta Testers
## Command: /my-new-command
### Test Scenarios
1. **Basic usage:**
- Run: `/my-new-command`
- Expected: [describe]
- Rate clarity: 1-5
2. **With arguments:**
- Run: `/my-new-command arg1 arg2`
- Expected: [describe]
- Rate usefulness: 1-5
3. **Error case:**
- Run: `/my-new-command invalid-input`
- Expected: Helpful error message
- Rate error message: 1-5
### Feedback Questions
1. Was the command easy to understand?
2. Did the output meet your expectations?
3. What would you change?
4. Would you use this command regularly?
```
## Testing Checklist
Before releasing a command:
### Structure
- [ ] File in correct location
- [ ] Correct .md extension
- [ ] Valid YAML frontmatter (if present)
- [ ] Markdown syntax correct
### Functionality
- [ ] Command appears in `/help`
- [ ] Description is clear
- [ ] Command executes without errors
- [ ] Arguments work as expected
- [ ] File references work
- [ ] Bash execution works (if used)
### Edge Cases
- [ ] Missing arguments handled
- [ ] Invalid arguments detected
- [ ] Non-existent files handled
- [ ] Special characters work
- [ ] Long inputs handled
### Integration
- [ ] Works with other commands
- [ ] Works with hooks (if applicable)
- [ ] Works with MCP (if applicable)
- [ ] State management works
### Quality
- [ ] Performance acceptable
- [ ] No security issues
- [ ] Error messages helpful
- [ ] Output formatted well
- [ ] Documentation complete
### Distribution
- [ ] Tested by others
- [ ] Feedback incorporated
- [ ] README updated
- [ ] Examples provided
## Debugging Failed Tests
### Common Issues and Solutions
**Issue: Command not appearing in /help**
```bash
# Check file location
ls -la .claude/commands/my-command.md
# Check permissions
chmod 644 .claude/commands/my-command.md
# Check syntax
head -n 20 .claude/commands/my-command.md
# Restart Claude Code
claude --debug
```
**Issue: Arguments not substituting**
```bash
# Verify syntax
grep '\$1' .claude/commands/my-command.md
grep '\$ARGUMENTS' .claude/commands/my-command.md
# Test with simple command first
echo "Test: \$1 and \$2" > .claude/commands/test-args.md
```
**Issue: Bash commands not executing**
```bash
# Check allowed-tools
grep "allowed-tools" .claude/commands/my-command.md
# Verify command syntax
grep '!\`' .claude/commands/my-command.md
# Test command manually
date
echo "test"
```
**Issue: File references not working**
```bash
# Check @ syntax
grep '@' .claude/commands/my-command.md
# Verify file exists
ls -la /path/to/referenced/file
# Check permissions
chmod 644 /path/to/referenced/file
```
## Best Practices
1. **Test early, test often**: Validate as you develop
2. **Automate validation**: Use scripts for repeatable checks
3. **Test edge cases**: Don't just test the happy path
4. **Get feedback**: Have others test before wide release
5. **Document tests**: Keep test scenarios for regression testing
6. **Monitor in production**: Watch for issues after release
7. **Iterate**: Improve based on real usage data

View File

@@ -0,0 +1,76 @@
---
name: daily-coding
description: Use for everyday coding tasks that involve writing or modifying source code.
version: 1.0.0
tags: [Coding, Daily, Checklist]
---
# Daily Coding Checklist
A minimal coding quality assurance checklist ensuring every code modification follows best practices.
## When to Use
Use this skill for:
- Implementing new features
- Adding code or modifying existing code
- User requests like "write a...", "implement...", "add...", or "modify..."
- Any coding task that involves Edit or Write tools
## When Not to Use
Do not use this skill for:
- Pure reading or understanding tasks with no modification intent
- Work already covered by specialized skills such as `bug-detective`, `architecture-design`, or `verification-loop`
- Configuration-only changes
- Documentation-only writing
## Core Checklist
### Before Starting
- [ ] **Read before modify** - Must read target file with Read tool before making changes
- [ ] **Understand context** - Confirm understanding of existing code logic and design intent
### During Coding
- [ ] **Minimal changes** - Only change what's necessary, no over-engineering, no unrelated features
- [ ] **Type safety** - Add type hints for Python, avoid `any` in TypeScript
- [ ] **Security check** - Avoid command injection, XSS, SQL injection vulnerabilities
### After Completion
- [ ] **Verify execution** - Ensure code runs correctly with no syntax errors
- [ ] **Clean up** - Remove print/console.log debug statements and temporary files
- [ ] **Brief summary** - Inform user what was changed and the scope of impact
## Quick Reference
### Common Mistakes to Avoid
```python
# ❌ Don't
def process(data=[]): # Mutable default argument
pass
# ✅ Should
def process(data: list | None = None):
data = data or []
```
```python
# ❌ Don't
except: # Bare except
pass
# ✅ Should
except ValueError as e:
logger.error(f"Processing failed: {e}")
raise
```
### Security Check Points
- User input must be validated/escaped
- Use pathlib for file paths, avoid path traversal
- Never hardcode sensitive info (API keys, passwords)

View File

@@ -0,0 +1,144 @@
---
name: daily-paper-generator
description: Use when the user asks to generate daily paper digests on a general topic. This skill supports both arXiv and bioRxiv (or either one), then produces structured Chinese/English summaries for selected papers.
version: 0.5.1
---
# Daily Paper Generator
## Overview
Discover, screen, and summarize recent papers for any research topic.
Supported sources:
- arXiv
- bioRxiv
- both (`--source both`)
Core workflow:
1. Define topic query and time window
2. Search papers from arXiv / bioRxiv
3. Select Top 10 candidates per field
4. Score and narrow to Top 3 per field
5. Choose Top 1 per field
6. Generate bilingual summaries
7. Save outputs to `daily paper/`
## When to Use
Use this skill when:
- The user asks for a daily/weekly paper digest on any topic
- The user wants recent papers from arXiv and/or bioRxiv
- The user needs structured bilingual notes for reading and tracking
## Output Format
Each summary should contain:
1. Paper title
2. Authors and venue/source
3. Link(s) and date
4. Chinese review (~300 words)
5. English review (concise academic prose)
6. Metadata table
7. Appendix (optional resources)
## Quick Reference
| Task | Method |
|---|---|
| Search papers | Use `scripts/arxiv_search.py` with `--source arxiv|biorxiv|both` |
| Topic selection | Use general-topic queries from `references/keywords.md` |
| Evaluate quality | Use `references/quality-criteria.md` |
| Write Chinese review | Use `references/writing-style.md` |
| Write English review | Follow scientific writing best practices |
## Workflow
### Step 1: Define query
Choose a concrete topic query. Examples:
- `test-time adaptation for medical imaging`
- `multimodal foundation model for healthcare`
- `protein language model interpretability`
### Step 2: Search arXiv and/or bioRxiv
Use helper script:
```bash
python skills/daily-paper-generator/scripts/arxiv_search.py \
--query "test-time adaptation for medical imaging" \
--source both \
--months 1 \
--max-results 80 \
--output /tmp/papers.json
```
Notes:
- `--source arxiv`: arXiv only
- `--source biorxiv`: bioRxiv only
- `--source both`: merge both sources and sort by date
### Step 3: Top 10 candidate selection (per field)
For each candidate paper:
1. Check topic relevance from title + abstract
2. Remove obviously off-topic papers
3. Keep **Top 10 candidates** for this field
Minimum rule:
- Do not jump directly from raw search results to final paper.
- Keep an explicit Top 10 list first.
### Step 4: Top 3 quality shortlist (per field)
For the Top 10 pool:
1. Score each paper with `references/quality-criteria.md`
2. Rank by weighted score
3. Keep **Top 3**
### Step 5: Final Top 1 selection (per field)
For the Top 3 shortlist:
1. Compare novelty + method completeness + experimental credibility
2. Check practical impact for the field
3. Select **Top 1** as the final pick
Required output trace:
- Top 10 candidate list
- Top 3 scored shortlist (with weighted scores)
- Final Top 1 and one-paragraph selection rationale
### Step 6: Generate bilingual summaries
For each selected paper, generate:
- 中文评语:背景、挑战、贡献、方法、结果、局限
- English Review: concise, factual, non-formulaic
### Step 7: Save output
Recommended directory and naming:
```text
daily paper/
YYYY-MM-DD-HHMM-paper-1.md
YYYY-MM-DD-HHMM-paper-2.md
YYYY-MM-DD-HHMM-paper-3.md
```
## Additional Resources
- `references/keywords.md`: general-topic query templates
- `references/quality-criteria.md`: scoring rubric
- `references/writing-style.md`: review writing style
- `example/daily paper example.md`: output example
- `scripts/arxiv_search.py`: arXiv + bioRxiv search helper
## Important Notes
1. Use explicit topic queries, avoid single-word vague queries.
2. Keep the time window explicit (`--months N`).
3. Distinguish source in metadata (`arxiv` vs `biorxiv`).
4. Use the fixed narrowing rule: **Top 10 -> Top 3 -> Top 1** (per field).
5. If a paper lacks robust evaluation, mark confidence and limitations clearly.
6. Do not fabricate unavailable fields (institution/GitHub/code links).

View File

@@ -0,0 +1,78 @@
# DeeperBrain: A Neuro-Grounded EEG Foundation Model Towards Universal BCI
## 作者及单位
Jiquan Wang, Sha Zhao, Yangxuan Zhou, Yiming Kang, Shijian Li, Gang Pan
Zhejiang University, College of Computer Science and Technology
## arXiv 链接
https://arxiv.org/abs/2601.06134
**发表日期**: 2026-01-05
**arXiv ID**: 2601.06134
**分类**: cs.LG, q-bio.NC, eess.SP
---
## 中文评语
通用脑机接口的发展受限于 EEG 信号的跨受试和跨任务泛化能力不足。现有基础模型大多采用通用深度学习架构,忽略了 EEG 信号的神经生理学特性和生物物理约束,且在冻结探针评估下效果有限。本研究提出 DeeperBrain一种神经驱动的 EEG 基础模型,将领域特定的归纳偏差整合到模型设计和学习目标中。在架构层面,该方法包含基于容积传导的通道编码和神经动力学感知的时间编码。在预训练层面,引入双目标策略:掩码 EEG 重建保证局部保真度神经动力学统计预测以强制与宏观脑状态对齐。实验结果显示DeeperBrain 在零样本跨受试迁移、跨任务泛化和少样本学习场景下优于现有基础模型。更重要的是,它在严格的冻结探针评估下保持优越效果,验证了将神经科学第一原理嵌入模型能够赋予学习表示通用 BCI 所需的泛化能力。
## English Review
Universal Brain-Computer Interfaces are constrained by the limited cross-subject and cross-task generalization of EEG signals. Most existing foundation models employ generic deep learning architectures that overlook neurophysiological characteristics and biophysical constraints, showing limited efficacy under frozen probing evaluation. This study presents DeeperBrain, a neuro-grounded EEG foundation model that integrates domain-specific inductive biases into both architecture design and learning objectives. The model incorporates volume conduction-based channel encoding and neurodynamics-aware temporal encoding to capture spatial and temporal patterns respectively. For pretraining, this study introduces a dual-objective strategy combining masked EEG reconstruction for local fidelity and neurodynamics statistics prediction to align with macroscopic brain states. Experiments show DeeperBrain outperforms existing foundation models across zero-shot cross-subject transfer, cross-task generalization, and few-shot learning scenarios. The model maintains strong performance under frozen probing evaluation, demonstrating that embedding neuroscientific first principles endows learned representations with the generalization needed for universal BCI.
## 主图
这里需要将论文的主图进行下载并存放。
---
## 论文元数据
| 项目 | 内容 |
|------|------|
| **标题** | DeeperBrain: A Neuro-Grounded EEG Foundation Model Towards Universal BCI |
| **第一作者** | Jiquan Wang |
| **作者列表** | Jiquan Wang, Sha Zhao, Yangxuan Zhou, Yiming Kang, Shijian Li, Gang Pan |
| **第一作者单位** | Zhejiang University, College of Computer Science and Technology |
| **发表日期** | 2026-01-05 |
| **arXiv 链接** | https://arxiv.org/abs/2601.06134 |
| **PDF 链接** | https://arxiv.org/pdf/2601.06134 |
| **分类** | cs.LG, q-bio.NC, eess.SP |
---
## 整合格式
Daily Paper 0126
DeeperBrain: A Neuro-Grounded EEG Foundation Model Towards Universal BCI
https://arxiv.org/abs/2601.06134
通用脑机接口的发展受限于 EEG 信号的跨受试和跨任务泛化能力不足。现有基础模型大多采用通用深度学习架构,忽略了 EEG 信号的神经生理学特性和生物物理约束,且在冻结探针评估下效果有限。本研究提出 DeeperBrain一种神经驱动的 EEG 基础模型,将领域特定的归纳偏差整合到模型设计和学习目标中。在架构层面,该方法包含基于容积传导的通道编码和神经动力学感知的时间编码。在预训练层面,引入双目标策略:掩码 EEG 重建保证局部保真度神经动力学统计预测以强制与宏观脑状态对齐。实验结果显示DeeperBrain 在零样本跨受试迁移、跨任务泛化和少样本学习场景下优于现有基础模型。更重要的是,它在严格的冻结探针评估下保持优越效果,验证了将神经科学第一原理嵌入模型能够赋予学习表示通用 BCI 所需的泛化能力。
Universal Brain-Computer Interfaces are constrained by the limited cross-subject and cross-task generalization of EEG signals. Most existing foundation models employ generic deep learning architectures that overlook neurophysiological characteristics and biophysical constraints, showing limited efficacy under frozen probing evaluation. This study presents DeeperBrain, a neuro-grounded EEG foundation model that integrates domain-specific inductive biases into both architecture design and learning objectives. The model incorporates volume conduction-based channel encoding and neurodynamics-aware temporal encoding to capture spatial and temporal patterns respectively. For pretraining, this study introduces a dual-objective strategy combining masked EEG reconstruction for local fidelity and neurodynamics statistics prediction to align with macroscopic brain states. Experiments show DeeperBrain outperforms existing foundation models across zero-shot cross-subject transfer, cross-task generalization, and few-shot learning scenarios. The model maintains strong performance under frozen probing evaluation, demonstrating that embedding neuroscientific first principles endows learned representations with the generalization needed for universal BCI.
## 附录
**github连接**未开源
**补充说明**
这篇论文的重要价值在于:
1. **跨学科融合**:将神经科学知识与深度学习结合
2. **可解释性**:神经驱动设计提高了模型的可解释性
3. **泛化能力**:在跨受试、跨任务场景下表现优异
4. **实用价值**:为通用 BCI 系统的开发提供了新方向
**Sources:**
- [arXiv Abstract](https://arxiv.org/abs/2601.06134)
- [arXiv HTML](https://arxiv.org/html/2601.06134v1)
- [Paperverse Review](https://paperverse.io/paper/eabc5d58-8762-4dc9-aaf3-665057852cb7)

View File

@@ -0,0 +1,71 @@
# General Topic Query Templates
## Query construction
Use this template:
`<task/problem> + <domain> + <method/constraint>`
Examples:
- `test-time adaptation + medical imaging + robustness`
- `multimodal retrieval + biomedicine + contrastive learning`
- `speech representation + low-resource + self-supervised learning`
## Topic starters
### Machine learning
- `test-time adaptation`
- `domain generalization`
- `uncertainty estimation`
- `causal representation learning`
### Multimodal and language
- `multimodal foundation model`
- `retrieval augmented generation`
- `vision-language model evaluation`
- `long-context reasoning`
### Bio/health
- `protein language model`
- `single-cell foundation model`
- `computational pathology`
- `clinical prediction model calibration`
### Neuroscience / BCI
- `EEG decoding`
- `speech decoding from EEG`
- `brain-computer interface`
- `neural signal representation learning`
## Source-specific tips
### arXiv
Search page pattern:
`https://arxiv.org/search/?searchtype=all&query=<QUERY>&abstracts=show&order=-announced_date_first`
API pattern:
`https://export.arxiv.org/api/query?search_query=all:<QUERY>&start=0&max_results=50&sortBy=submittedDate&sortOrder=descending`
### bioRxiv
Use API by date range and then filter by query text:
`https://api.biorxiv.org/details/biorxiv/<FROM_DATE>/<TO_DATE>/<CURSOR>`
Example:
`https://api.biorxiv.org/details/biorxiv/2026-01-01/2026-04-23/0`
## Practical defaults
- Query length: 3 to 8 words
- Time range: last 3 months (`--months 3`)
- Sources: `--source both`
- Result cap: `--max-results 50`
## Anti-patterns
- Too broad: `AI`, `biology`, `vision`
- Too narrow with hard constraints before retrieval
- Mixing too many unrelated concepts in one query

View File

@@ -0,0 +1,124 @@
# 论文质量评审标准
## 评审维度与权重
| 维度 | 权重 | 说明 |
|------|------|------|
| **创新性** | 30% | 论文的创新程度和贡献的新颖性 |
| **方法完整性** | 25% | 方法的描述完整性和可复现性 |
| **实验充分性** | 25% | 实验设计的全面性和结果的可信度 |
| **写作质量** | 10% | 论文表达的清晰度和学术规范性 |
| **相关性与影响力** | 10% | 与领域的相关性和潜在影响力 |
## 详细评分标准
### 1. 创新性 (30%)
| 分数 | 标准 |
|------|------|
| **5分 - 突破性贡献** | 提出全新的范式或方法,对领域有重大影响 |
| **4分 - 显著创新** | 在现有方法上有显著改进,提出新的见解 |
| **3分 - 方法创新** | 提出了新的方法或框架,有一定的创新性 |
| **2分 - 改进型** | 对现有方法有改进,但创新有限 |
| **1分 - 增量改进** | 仅有微小的改进或组合现有方法 |
**评估要点:**
- 是否提出了新的问题或视角?
- 方法是否有实质性创新?
- 是否突破了现有方法的局限?
### 2. 方法完整性 (25%)
| 分数 | 标准 |
|------|------|
| **5分 - 完整且严谨** | 方法描述完整,数学推导严谨,易于复现 |
| **4分 - 非常完整** | 方法描述详细,大部分细节可复现 |
| **3分 - 可复现** | 核心方法清晰,可基本复现 |
| **2分 - 缺乏细节** | 关键细节缺失,复现困难 |
| **1分 - 表述不清** | 方法描述不清楚,无法判断有效性 |
**评估要点:**
- 方法描述是否清晰?
- 是否提供了足够的细节?
- 是否有代码仓库?
- 数学推导是否严谨?
### 3. 实验充分性 (25%)
| 分数 | 标准 |
|------|------|
| **5分 - 全面深入** | 多数据集验证,充分消融实验,详细分析 |
| **4分 - 非常充分** | 多个数据集,合理消融实验 |
| **3分 - 合理验证** | 主干实验完整,结果可信 |
| **2分 - 验证不足** | 实验较少,缺乏对比 |
| **1分 - 实验不足** | 仅在简单场景验证,结果不可信 |
**评估要点:**
- 是否在标准数据集上验证?
- 是否有充分的对比实验?
- 是否有消融实验?
- 统计显著性如何?
### 4. 写作质量 (10%)
| 分数 | 标准 |
|------|------|
| **5分 - 优秀** | 表达清晰,逻辑严密,学术规范 |
| **4分 - 良好** | 表达清楚,逻辑基本完整 |
| **3分 - 清晰** - 表达基本清晰,可理解 |
| **2分 - 一般** | 表述有模糊之处 |
| **1分 - 表述不清** | 表述混乱,难以理解 |
### 5. 相关性与影响力 (10%)
| 分数 | 标准 |
|------|------|
| **5分 - 广泛影响** | 解决重要问题,影响多个领域 |
| **4分 - 领域重要** | 解决领域内重要问题 |
| **3分 - 相关有意义** - 研究有意义,有一定影响 |
| **2分 - 小众问题** | 针对小众问题 |
| **1分 - 影响有限** - 影响非常有限 |
## 自动评分辅助指标
在人工评审前,可使用以下指标辅助初筛:
- **摘要质量**:摘要是否包含实验结果和具体数据
- **数据集**:是否在知名数据集上验证(如 TUH EEG, BCIC IV 等)
- **代码可用性**:是否提供 GitHub 链接
- **作者机构**:第一作者/机构的学术声誉(可选)
- **引用数**arXiv 上的早期引用数(可选)
## 综合评分计算
```
总分 = 创新性×0.30 + 方法完整性×0.25 + 实验充分性×0.25 + 写作质量×0.10 + 相关性与影响力×0.10
```
**评分示例:**
- 创新性4分
- 方法完整性3分
- 实验充分性4分
- 写作质量3分
- 相关性与影响力4分
总分 = 4×0.30 + 3×0.25 + 4×0.25 + 3×0.10 + 4×0.10 = 1.2 + 0.75 + 1.0 + 0.3 + 0.4 = 3.65
## 评审流程
1. **初筛**:根据标题和摘要排除明显不相关的论文
2. **Top 10 候选池**:每个领域先固定保留 Top 10
3. **全文阅读**:对 Top 10 进行深度阅读/细读摘要与方法实验部分
4. **维度打分**按照5个维度逐一打分
5. **计算总分**:加权计算综合得分
6. **Top 3 shortlist**:按总分排序,选出 Top 3
7. **Top 1 final**:在 Top 3 中结合创新性、实验可信度和领域影响力选出 Top 1
## 固定收敛规则(每个领域)
- 必须遵循:**Top 10 -> Top 3 -> Top 1**
- 不允许从原始检索结果直接跳到最终 Top 1
- 输出必须可审计,至少包含:
- Top 10 候选列表
- Top 3 评分表(五维分数 + 加权总分)
- Top 1 选择理由

View File

@@ -0,0 +1,134 @@
# 中文评语写作风格指南
基于 AINet Daily Paper.xlsx 中高质量示例的写作风格总结。
## 评语结构
中文评语约 300 字,遵循以下结构:
```
1. 背景 (1-2句) ──> 介绍研究领域的背景和重要性
2. 挑战 (2-3句) ──> 指出现有方法面临的关键问题
3. 贡献 (1-2句) ──> 概述本工作的核心贡献
4. 方法 (2-3句) ──> 描述提出的方法/模型的关键技术
5. 实验结果 (2-3句) ──> 总结主要实验发现和性能指标
6. 分析与局限 (1-2句) ──> 分析结果意义,指出局限性
```
## 常用句式模板
### 开头(背景)
- `本文针对...问题`
- `本研究聚焦于...`
- `本文探讨了...这一基本挑战`
- `...始终面临诸多挑战`
### 挑战描述
- `尽管...,但现有方法面临...`
- `然而,现有方法存在...`
- `...高度异构,而以往...难以兼顾...`
- `针对这些问题,本文提出...`
### 方法描述
- `为此,本文提出...`
- `该研究提出...`
- `本文提出...,一种...`
- `该方法通过...`
### 实验结果
- `实验结果表明...`
- `在...数据集上,该方法...`
- `实验在...上取得了...`
- `结果表明,...`
### 分析与局限
- `从而验证了...的可行性`
- `为...奠定方法学基础`
- `该工作打破了...`
- `从而验证了...在实际应用中的可行性`
## 高质量示例分析
### 示例 1ECHO (Toward Contextual Seq2Seq Paradigms in Large EEG Models)
**结构分析:**
```
[背景] 从脑电信号中统一刻画和理解多样化认知任务始终面临诸多挑战
[挑战] 不同任务形式与标签空间差异显著,不同数据集在电极布局和采集范式上高度异构,
而以往以编码器为中心、依赖任务专用预测头的建模方式难以兼顾泛化性与灵活性
[方法] 为此,本文提出 ECHO一种以解码器为核心的大规模脑电建模范式
将 EEG 分析重构为统一的序列到序列学习问题
[技术细节] 该方法将连续脑电片段、任务标识与标签符号共同组织进自回归解码序列中,
使模型能够在同一框架下理解任务语境并生成对应预测
[实验] 在涵盖 12 个公开数据集、6 类脑电任务的统一多任务评测中,
ECHO 在整体性能、跨数据集泛化以及零样本场景下均显著优于多种代表性基线方法
[意义] 为新一代灵活、可扩展的脑机接口系统奠定方法学基础
```
### 示例 2EEG-to-Voice Decoding
**结构分析:**
```
[背景] 本研究聚焦于从非侵入式 EEG 信号中重建有声语音与想象语音,
以辅助存在言语障碍的个体进行交流
[方法] 其技术框架包括一个被试特异的生成器,以开环方式将预处理后的 EEG 信号映射为 Mel 频谱
[技术细节] 随后通过预训练的 HiFi-GAN 声码器和 HuBERT ASR 模块生成语音波形并解码文本
[创新点] 该方法避免了显式的时间对齐过程,采用迁移学习将基于有声语音预训练的生成器
适配到想象语音任务中,并使用双损失函数进行训练
[实验结果] 在有声语音和想象语音两种情形下均实现了稳定的声学重建性能和语言层面的重建性能
[额外特点] 在语句长度增加的情况下仍能保持文本层面的解码性能
[意义] 从而验证了 EEG 到语音通信在实际应用中的可行性
```
## 写作要点
### 1. 学术语言规范
- 使用正式的学术书面语
- 避免口语化表达
- 使用精确的技术术语
### 2. 逻辑连贯
- 各部分之间有清晰的逻辑关系
- 使用恰当的连接词(然而、为此、从而、同时)
- 从问题到解决方案到验证结果
### 3. 信息密度
- 每句话都承载有效信息
- 避免冗余表述
- 突出核心贡献
### 4. 客观评价
- 准确描述实验结果
- 指出方法的局限性
- 不夸大成果
## 英文评语写作
英文评语应与中文评语对应,保持流畅的学术英语风格:
- 使用正式的学术英语
- 保持与中文评语相同的结构
- 注意时态一致性(描述论文内容用现在时,描述实验结果用过去时)
- 使用准确的学术词汇
### 常用句式
**Opening:**
- `This paper addresses the...`
- `This study focuses on...`
- `The paper proposes...`
**Problem:**
- `While existing...`
- `However, current methods face...`
- `Despite progress in...`
**Method:**
- `To tackle this, the research proposes...`
- `The authors present...`
- `This work introduces...`
**Results:**
- `Experiments demonstrate that...`
- `The findings show...`
- `Results indicate that...`

View File

@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""
Research paper search helper for arXiv and bioRxiv.
Usage:
python arxiv_search.py --query "test-time adaptation" --source both --max-results 30
python arxiv_search.py --keywords multimodal representation learning --source arxiv
python arxiv_search.py --query "protein language model" --source biorxiv --months 6
"""
from __future__ import annotations
import argparse
import json
import re
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from urllib.parse import quote_plus
from urllib.request import urlopen
import feedparser
def _safe_parse_date(value: str) -> Optional[datetime]:
if not value:
return None
for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S"):
try:
return datetime.strptime(value[:19], fmt)
except ValueError:
continue
return None
def _in_time_window(date_text: str, months: int) -> bool:
parsed = _safe_parse_date(date_text)
if parsed is None:
return True
cutoff = datetime.now() - timedelta(days=months * 30)
return parsed >= cutoff
def _token_match(text: str, query: str) -> bool:
query_tokens = [t.lower() for t in re.split(r"\s+", query.strip()) if t.strip()]
if not query_tokens:
return True
hay = text.lower()
return all(tok in hay for tok in query_tokens)
def search_arxiv(
query: str,
max_results: int = 50,
categories: Optional[List[str]] = None,
months: int = 3,
) -> List[Dict]:
base_url = "https://export.arxiv.org/api/query?"
if categories:
cat_query = " OR ".join([f"cat:{cat}" for cat in categories])
search_query = f"search_query=({quote_plus(cat_query)})+AND+all:{quote_plus(query)}"
else:
search_query = f"search_query=all:{quote_plus(query)}"
params = f"&start=0&max_results={max_results}&sortBy=submittedDate&sortOrder=descending"
url = base_url + search_query + params
print(f"[arXiv] searching: {url}")
feed = feedparser.parse(url)
papers: List[Dict] = []
for entry in feed.entries:
published = datetime(*entry.published_parsed[:6])
if not _in_time_window(published.strftime("%Y-%m-%d"), months):
continue
authors = [author.name for author in entry.authors] if getattr(entry, "authors", None) else []
first_author = authors[0] if authors else "Unknown"
arxiv_id = entry.id.split("/abs/")[-1]
arxiv_link = f"https://arxiv.org/abs/{arxiv_id}"
summary = re.sub(r"\s+", " ", entry.summary).strip()
papers.append(
{
"source": "arxiv",
"title": entry.title.strip(),
"authors": authors,
"first_author": first_author,
"summary": summary,
"published": published.strftime("%Y-%m-%d"),
"id": arxiv_id,
"arxiv_id": arxiv_id,
"link": arxiv_link,
"arxiv_link": arxiv_link,
"pdf_link": f"https://arxiv.org/pdf/{arxiv_id}.pdf",
"categories": [tag.term for tag in getattr(entry, "tags", [])],
}
)
print(f"[arXiv] found {len(papers)} papers in last {months} month(s)")
return papers
def search_biorxiv(query: str, max_results: int = 50, months: int = 3) -> List[Dict]:
end_date = datetime.now().date()
start_date = (datetime.now() - timedelta(days=months * 30)).date()
cursor = 0
page_size = 100
papers: List[Dict] = []
# bioRxiv API may reject future date ranges in environments with shifted system dates.
# Probe and step back by year until the API accepts the interval.
shift_days = 0
while True:
probe_start = start_date - timedelta(days=shift_days)
probe_end = end_date - timedelta(days=shift_days)
probe_url = (
"https://api.biorxiv.org/details/biorxiv/"
f"{probe_start.isoformat()}/{probe_end.isoformat()}/0"
)
with urlopen(probe_url, timeout=30) as response:
probe_payload = json.loads(response.read().decode("utf-8"))
status = (
probe_payload.get("messages", [{}])[0].get("status", "").strip().lower()
)
if status != "not available at this time":
break
shift_days += 365
if shift_days > 365 * 8:
print("[bioRxiv] API unavailable for probed date ranges.")
return []
if shift_days:
print(
"[bioRxiv] adjusted date window for API availability: "
f"{probe_start.isoformat()} to {probe_end.isoformat()}"
)
while len(papers) < max_results:
window_start = start_date - timedelta(days=shift_days)
window_end = end_date - timedelta(days=shift_days)
url = (
"https://api.biorxiv.org/details/biorxiv/"
f"{window_start.isoformat()}/{window_end.isoformat()}/{cursor}"
)
print(f"[bioRxiv] fetching: {url}")
with urlopen(url, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8"))
collection = payload.get("collection", [])
if not collection:
break
for item in collection:
title = item.get("title", "").strip()
abstract = re.sub(r"\s+", " ", item.get("abstract", "")).strip()
merged_text = f"{title} {abstract}"
if not _token_match(merged_text, query):
continue
published = item.get("date", "")
if not _in_time_window(published, months):
continue
author_text = item.get("authors", "")
authors = [a.strip() for a in re.split(r";|,", author_text) if a.strip()]
first_author = authors[0] if authors else "Unknown"
doi = item.get("doi", "").strip()
version = str(item.get("version", "1")).strip() or "1"
if doi:
link = f"https://www.biorxiv.org/content/{doi}v{version}"
else:
link = item.get("url", "")
papers.append(
{
"source": "biorxiv",
"title": title,
"authors": authors,
"first_author": first_author,
"summary": abstract,
"published": published,
"id": doi or item.get("title", "")[:80],
"doi": doi,
"link": link,
"pdf_link": f"{link}.full.pdf" if link else "",
"categories": [item.get("category", "")],
}
)
if len(papers) >= max_results:
break
if len(collection) < page_size:
break
cursor += page_size
print(f"[bioRxiv] found {len(papers)} papers in last {months} month(s)")
return papers
def search_papers(
query: str,
source: str,
max_results: int,
months: int,
categories: Optional[List[str]],
) -> List[Dict]:
if source == "arxiv":
return search_arxiv(query=query, max_results=max_results, categories=categories, months=months)
if source == "biorxiv":
return search_biorxiv(query=query, max_results=max_results, months=months)
# both
per_source = max(10, max_results)
arxiv = search_arxiv(query=query, max_results=per_source, categories=categories, months=months)
biorxiv = search_biorxiv(query=query, max_results=per_source, months=months)
merged = arxiv + biorxiv
merged.sort(key=lambda x: x.get("published", ""), reverse=True)
return merged[:max_results]
def print_papers(papers: List[Dict], limit: int = 10) -> None:
print(f"\n=== Top {min(limit, len(papers))} paper(s) ===\n")
for i, paper in enumerate(papers[:limit], start=1):
print(f"[{i}] ({paper.get('source', 'unknown')}) {paper.get('title', 'Untitled')}")
print(f" Authors: {paper.get('first_author', 'Unknown')} et al.")
print(f" Date: {paper.get('published', 'Unknown')}")
print(f" Link: {paper.get('link', '')}")
summary = paper.get("summary", "")
print(f" Abstract: {summary[:150]}...")
print()
def main() -> None:
parser = argparse.ArgumentParser(description="Search papers from arXiv and bioRxiv")
parser.add_argument("--query", "-q", type=str, help="search query")
parser.add_argument("--keywords", "-k", nargs="+", help="keyword list")
parser.add_argument("--source", "-s", choices=["arxiv", "biorxiv", "both"], default="both")
parser.add_argument("--max-results", "-n", type=int, default=50, help="max number of returned papers")
parser.add_argument(
"--categories",
"-c",
nargs="+",
default=["cs.CV", "cs.LG", "cs.AI", "q-bio.NC"],
help="arXiv categories (used only when source includes arxiv)",
)
parser.add_argument("--months", "-m", type=int, default=3, help="only keep papers from last N months")
parser.add_argument("--output", "-o", type=str, help="output JSON path")
args = parser.parse_args()
if args.query:
query = args.query.strip()
elif args.keywords:
query = " ".join(args.keywords).strip()
else:
query = "machine learning"
papers = search_papers(
query=query,
source=args.source,
max_results=args.max_results,
months=args.months,
categories=args.categories,
)
print_papers(papers, limit=10)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
json.dump(papers, f, ensure_ascii=False, indent=2)
print(f"\nSaved results to: {args.output}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,17 @@
---
name: defuddle
description: Extract clean Markdown from web pages. In the KB workflow, use it as a utility under obsidian-source-ingestion.
---
# Defuddle
Use Defuddle as a utility for `obsidian-source-ingestion`.
Typical KB target for web content:
- `Sources/Web/`
Typical command:
```bash
defuddle parse <url> --md
```

View File

@@ -0,0 +1,390 @@
---
name: doc-coauthoring
description: This skill should be used when the user asks to co-author documentation, draft a proposal, write a technical spec, create a decision doc or RFC, or structure a substantial document through iterative collaboration and reader testing.
version: 0.1.0
---
# Doc Co-Authoring Workflow
This skill provides a structured workflow for guiding users through collaborative document creation. Act as an active guide, walking users through three stages: Context Gathering, Refinement & Structure, and Reader Testing.
## Runtime contract
Use `references/RUNTIME-MATRIX.md` to decide what is available in the current environment before offering connectors, artifacts, or reader-test subagents.
If no artifact-like surface is available, default to a normal markdown file in a user-specified path or an explicitly named working file. Do not assume artifacts are available.
## When to Offer This Workflow
**Trigger conditions:**
- User mentions writing documentation: "write a doc", "draft a proposal", "create a spec", "write up"
- User mentions specific doc types: "PRD", "design doc", "decision doc", "RFC"
- User seems to be starting a substantial writing task
**Initial offer:**
Offer the user a structured workflow for co-authoring the document. Explain the three stages:
1. **Context Gathering**: User provides all relevant context while Claude asks clarifying questions
2. **Refinement & Structure**: Iteratively build each section through brainstorming and editing
3. **Reader Testing**: Test the doc with a fresh Claude (no context) to catch blind spots before others read it
Explain that this approach helps ensure the doc works well when others read it (including when they paste it into Claude). Ask if they want to try this workflow or prefer to work freeform.
If user declines, work freeform. If user accepts, proceed to Stage 1.
## Stage 1: Context Gathering
**Goal:** Close the gap between what the user knows and what Claude knows, enabling smart guidance later.
### Initial Questions
Start by asking the user for meta-context about the document:
1. What type of document is this? (e.g., technical spec, decision doc, proposal)
2. Who's the primary audience?
3. What's the desired impact when someone reads this?
4. Is there a template or specific format to follow?
5. Any other constraints or context to know?
Inform them they can answer in shorthand or dump information however works best for them.
**If user provides a template or mentions a doc type:**
- Ask if they have a template document to share
- If they provide a link to a shared document, use the appropriate integration to fetch it
- If they provide a file, read it
**If user mentions editing an existing shared document:**
- Use the appropriate integration to read the current state
- Check for images without alt-text
- If images exist without alt-text, explain that when others use Claude to understand the doc, Claude won't be able to see them. Ask if they want alt-text generated. If so, request they paste each image into chat for descriptive alt-text generation.
### Info Dumping
Once initial questions are answered, encourage the user to dump all the context they have. Request information such as:
- Background on the project/problem
- Related team discussions or shared documents
- Why alternative solutions aren't being used
- Organizational context (team dynamics, past incidents, politics)
- Timeline pressures or constraints
- Technical architecture or dependencies
- Stakeholder concerns
Advise them not to worry about organizing it - just get it all out. Offer multiple ways to provide context:
- Info dump stream-of-consciousness
- Point to team channels or threads to read
- Link to shared documents
**If integrations are available** (e.g., Slack, Teams, Google Drive, SharePoint, or other MCP servers), mention that these can be used to pull in context directly.
**If no integrations are detected and in Claude.ai or Claude app:** Suggest they can enable connectors in their Claude settings to allow pulling context from messaging apps and document storage directly.
Inform them clarifying questions will be asked once they've done their initial dump.
**During context gathering:**
- If user mentions team channels or shared documents:
- If integrations available: Inform them the content will be read now, then use the appropriate integration
- If integrations not available: Explain lack of access. Suggest they enable connectors in Claude settings, or paste the relevant content directly.
- If user mentions entities/projects that are unknown:
- Ask if connected tools should be searched to learn more
- Wait for user confirmation before searching
- As user provides context, track what's being learned and what's still unclear
**Asking clarifying questions:**
When user signals they've done their initial dump (or after substantial context provided), ask clarifying questions to ensure understanding:
Generate 5-10 numbered questions based on gaps in the context.
Inform them they can use shorthand to answer (e.g., "1: yes, 2: see #channel, 3: no because backwards compat"), link to more docs, point to channels to read, or just keep info-dumping. Whatever's most efficient for them.
**Exit condition:**
Sufficient context has been gathered when questions show understanding - when edge cases and trade-offs can be asked about without needing basics explained.
**Transition:**
Ask if there's any more context they want to provide at this stage, or if it's time to move on to drafting the document.
If user wants to add more, let them. When ready, proceed to Stage 2.
## Stage 2: Refinement & Structure
**Goal:** Build the document section by section through brainstorming, curation, and iterative refinement.
**Instructions to user:**
Explain that the document will be built section by section. For each section:
1. Clarifying questions will be asked about what to include
2. 5-20 options will be brainstormed
3. User will indicate what to keep/remove/combine
4. The section will be drafted
5. It will be refined through surgical edits
Start with whichever section has the most unknowns (usually the core decision/proposal), then work through the rest.
**Section ordering:**
If the document structure is clear:
Ask which section they'd like to start with.
Suggest starting with whichever section has the most unknowns. For decision docs, that's usually the core proposal. For specs, it's typically the technical approach. Summary sections are best left for last.
If user doesn't know what sections they need:
Based on the type of document and template, suggest 3-5 sections appropriate for the doc type.
Ask if this structure works, or if they want to adjust it.
**Once structure is agreed:**
Create the initial document structure with placeholder text for all sections.
**If access to artifacts is available:**
Use `create_file` to create an artifact. This gives both Claude and the user a scaffold to work from.
Inform them that the initial structure with placeholders for all sections will be created.
Create artifact with all section headers and brief placeholder text like "[To be written]" or "[Content here]".
Provide the scaffold link and indicate it's time to fill in each section.
**If no access to artifacts:**
Create a markdown file in the working directory. Name it appropriately (e.g., `decision-doc.md`, `technical-spec.md`).
Inform them that the initial structure with placeholders for all sections will be created.
Create file with all section headers and placeholder text.
Confirm the filename has been created and indicate it's time to fill in each section.
**For each section:**
### Step 1: Clarifying Questions
Announce work will begin on the [SECTION NAME] section. Ask 5-10 clarifying questions about what should be included:
Generate 5-10 specific questions based on context and section purpose.
Inform them they can answer in shorthand or just indicate what's important to cover.
### Step 2: Brainstorming
For the [SECTION NAME] section, brainstorm [5-20] things that might be included, depending on the section's complexity. Look for:
- Context shared that might have been forgotten
- Angles or considerations not yet mentioned
Generate 5-20 numbered options based on section complexity. At the end, offer to brainstorm more if they want additional options.
### Step 3: Curation
Ask which points should be kept, removed, or combined. Request brief justifications to help learn priorities for the next sections.
Provide examples:
- "Keep 1,4,7,9"
- "Remove 3 (duplicates 1)"
- "Remove 6 (audience already knows this)"
- "Combine 11 and 12"
**If user gives freeform feedback** (e.g., "looks good" or "I like most of it but...") instead of numbered selections, extract their preferences and proceed. Parse what they want kept/removed/changed and apply it.
### Step 4: Gap Check
Based on what they've selected, ask if there's anything important missing for the [SECTION NAME] section.
### Step 5: Drafting
Use `str_replace` to replace the placeholder text for this section with the actual drafted content.
Announce the [SECTION NAME] section will be drafted now based on what they've selected.
**If using artifacts:**
After drafting, provide a link to the artifact.
Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
**If using a file (no artifacts):**
After drafting, confirm completion.
Inform them the [SECTION NAME] section has been drafted in [filename]. Ask them to read through it and indicate what to change. Note that being specific helps learning for the next sections.
**Key instruction for user (include when drafting the first section):**
Provide a note: Instead of editing the doc directly, ask them to indicate what to change. This helps learning of their style for future sections. For example: "Remove the X bullet - already covered by Y" or "Make the third paragraph more concise".
### Step 6: Iterative Refinement
As user provides feedback:
- Use `str_replace` to make edits (never reprint the whole doc)
- **If using artifacts:** Provide link to artifact after each edit
- **If using files:** Just confirm edits are complete
- If user edits doc directly and asks to read it: mentally note the changes they made and keep them in mind for future sections (this shows their preferences)
**Continue iterating** until user is satisfied with the section.
### Quality Checking
After 3 consecutive iterations with no substantial changes, ask if anything can be removed without losing important information.
When section is done, confirm [SECTION NAME] is complete. Ask if ready to move to the next section.
**Repeat for all sections.**
### Near Completion
As approaching completion (80%+ of sections done), announce intention to re-read the entire document and check for:
- Flow and consistency across sections
- Redundancy or contradictions
- Anything that feels like "slop" or generic filler
- Whether every sentence carries weight
Read entire document and provide feedback.
**When all sections are drafted and refined:**
Announce all sections are drafted. Indicate intention to review the complete document one more time.
Review for overall coherence, flow, completeness.
Provide any final suggestions.
Ask if ready to move to Reader Testing, or if they want to refine anything else.
## Stage 3: Reader Testing
**Goal:** Test the document with a fresh Claude (no context bleed) to verify it works for readers.
**Instructions to user:**
Explain that testing will now occur to see if the document actually works for readers. This catches blind spots - things that make sense to the authors but might confuse others.
### Testing Approach
**If access to sub-agents is available (e.g., in Claude Code):**
Perform the testing directly without user involvement.
### Step 1: Predict Reader Questions
Announce intention to predict what questions readers might ask when trying to discover this document.
Generate 5-10 questions that readers would realistically ask.
### Step 2: Test with Sub-Agent
Announce that these questions will be tested with a fresh Claude instance (no context from this conversation).
For each question, invoke a sub-agent with just the document content and the question.
Summarize what Reader Claude got right/wrong for each question.
### Step 3: Run Additional Checks
Announce additional checks will be performed.
Invoke sub-agent to check for ambiguity, false assumptions, contradictions.
Summarize any issues found.
### Step 4: Report and Fix
If issues found:
Report that Reader Claude struggled with specific issues.
List the specific issues.
Indicate intention to fix these gaps.
Loop back to refinement for problematic sections.
---
**If no access to sub-agents (e.g., claude.ai web interface):**
The user will need to do the testing manually.
### Step 1: Predict Reader Questions
Ask what questions people might ask when trying to discover this document. What would they type into Claude.ai?
Generate 5-10 questions that readers would realistically ask.
### Step 2: Setup Testing
Provide testing instructions:
1. Open a fresh Claude conversation: https://claude.ai
2. Paste or share the document content (if using a shared doc platform with connectors enabled, provide the link)
3. Ask Reader Claude the generated questions
For each question, instruct Reader Claude to provide:
- The answer
- Whether anything was ambiguous or unclear
- What knowledge/context the doc assumes is already known
Check if Reader Claude gives correct answers or misinterprets anything.
### Step 3: Additional Checks
Also ask Reader Claude:
- "What in this doc might be ambiguous or unclear to readers?"
- "What knowledge or context does this doc assume readers already have?"
- "Are there any internal contradictions or inconsistencies?"
### Step 4: Iterate Based on Results
Ask what Reader Claude got wrong or struggled with. Indicate intention to fix those gaps.
Loop back to refinement for any problematic sections.
---
### Exit Condition (Both Approaches)
When Reader Claude consistently answers questions correctly and doesn't surface new gaps or ambiguities, the doc is ready.
## Final Review
When Reader Testing passes:
Announce the doc has passed Reader Claude testing. Before completion:
1. Recommend they do a final read-through themselves - they own this document and are responsible for its quality
2. Suggest double-checking any facts, links, or technical details
3. Ask them to verify it achieves the impact they wanted
Ask if they want one more review, or if the work is done.
**If user wants final review, provide it. Otherwise:**
Announce document completion. Provide a few final tips:
- Consider linking this conversation in an appendix so readers can see how the doc was developed
- Use appendices to provide depth without bloating the main doc
- Update the doc as feedback is received from real readers
## Tips for Effective Guidance
**Tone:**
- Be direct and procedural
- Explain rationale briefly when it affects user behavior
- Don't try to "sell" the approach - just execute it
**Handling Deviations:**
- If user wants to skip a stage: Ask if they want to skip this and write freeform
- If user seems frustrated: Acknowledge this is taking longer than expected. Suggest ways to move faster
- Always give user agency to adjust the process
**Context Management:**
- Throughout, if context is missing on something mentioned, proactively ask
- Don't let gaps accumulate - address them as they come up
**Artifact Management:**
- Use `create_file` for drafting full sections
- Use `str_replace` for all edits
- Provide artifact link after every change
- Never use artifacts for brainstorming lists - that's just conversation
**Quality over Speed:**
- Don't rush through stages
- Each iteration should make meaningful improvements
- The goal is a document that actually works for readers
## Reference Files
Load only what is needed:
- `references/RUNTIME-MATRIX.md` - how to adapt the workflow to Claude Code, Claude.ai, connector-rich, and connector-poor environments
- `references/DOC-TYPES.md` - default section scaffolds for common document types
- `references/READER-TEST.md` - reader-testing prompts, handoff package, and pass/fail signals

View File

@@ -0,0 +1,30 @@
# Document Type Scaffolds
## Decision doc
- Context
- Decision
- Alternatives considered
- Risks
- Rollout / next steps
## Technical spec
- Problem
- Requirements
- Proposed design
- Data / API changes
- Failure modes
- Validation plan
## Proposal
- Motivation
- Proposed work
- Expected impact
- Risks and dependencies
- Ask / timeline
## RFC
- Background
- Proposal
- Open questions
- Compatibility / migration
- Decision record

View File

@@ -0,0 +1,16 @@
# Reader Test
## Goal
Use a fresh-reader pass to find blind spots, unclear assumptions, and missing context.
## Handoff package
Provide the tester with:
- document path,
- intended audience,
- expected action after reading,
- any non-obvious constraints.
## Pass criteria
- reader can explain the decision or proposal back accurately,
- reader can identify next actions,
- reader does not need hidden author context to follow the doc.

View File

@@ -0,0 +1,18 @@
# Runtime Matrix
## Claude Code / local filesystem available
- Prefer local markdown files.
- Use direct file edits instead of artifact-only assumptions.
- Use sub-agents for reader testing only when they are actually available.
## Claude.ai or app with artifacts
- Use artifacts when they improve iteration speed.
- Keep the document path or artifact identity explicit in the conversation.
## Connectors available
- Pull context from connected systems only after user consent.
- Summarize imported context before drafting.
## No connectors available
- Ask the user to paste or summarize the needed context.
- Do not imply that Slack / Drive / SharePoint can be read automatically.

View File

@@ -0,0 +1,208 @@
<div align="center">
<strong>Language</strong>: <a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
</div>
# Expression Skill
Conclusion-first communication for technical work, writing and editing, documentation, multi-step tasks, and verification-heavy workflows.
## Overview
`expression-skill` is a reusable communication skill for assistants that need to be:
- concrete,
- concise,
- checkable,
- and useful under real task pressure.
It is designed for cases where the user does not want background narration. The user wants a decision, an execution path, a reviewable summary, or a clear next step.
## Design Goal
This skill optimizes for the shortest reliable path from a user problem to:
- a decision,
- a command,
- a file-level summary,
- a verified status update,
- or a reusable artifact.
It does not optimize for sounding exhaustive. It optimizes for lowering decision cost, implementation cost, and review cost.
## Core Communication Model
Every substantial response should make three things visible:
1. what is true,
2. why it matters,
3. what should happen next.
Default priority:
1. conclusion
2. evidence or reason
3. risk, uncertainty, or boundary
4. concrete action
5. reusable next step
## What This Skill Enforces
### 1. Conclusion First
Lead with the main judgment. Do not hide it behind setup or narration.
### 2. Concrete Over Abstract
Prefer:
- commands,
- paths,
- counts,
- checks,
- examples,
- observable behavior.
Avoid vague process language unless it is followed by a concrete action.
### 3. Clarify Only When It Changes the Result
Ask questions only when ambiguity changes:
- the goal,
- the target object,
- the success criteria,
- the constraints,
- or the implementation path.
Do not ask for facts that can be read from files, configs, docs, or command output.
### 4. Risks Early
If there is uncertainty, a destructive boundary, or a likely failure mode, say it early instead of hiding it at the end.
### 5. Subtraction
Remove background that does not change the decision. Merge repeated reasons. Demote low-priority branches. Stop when the next useful action is clear.
## Default Workflow
Before answering a non-trivial request:
1. Identify the user's practical purpose.
2. Clarify the task only if ambiguity would change the outcome.
3. Read discoverable facts before asking about them.
4. Form one core sentence.
5. Add only the minimum support needed to make it credible.
6. Surface the main risk or boundary early.
7. End with the smallest useful next step.
## Scenario Rules
### Coding
Lead with what changed or what should change. Include files, commands, and verification. Do not narrate every exploration step.
### File Operations
Always report:
- input path
- output path
- changed files
- untouched files
- verification performed
### Long-Running Work
Provide visible roadmarks:
- step / total
- processed amount
- output path
- next checkpoint
- visible blocker
### Writing and Editing
Prefer compressed claims over inflated wording. Make the contribution, evidence, and limitation visible.
### Technical Discussion
Separate fact, inference, and recommendation. Surface weak assumptions early.
### Knowledge Work
State the knowledge problem first: decision, evidence trail, synthesis, reusable method, or practice artifact.
## Critique Framework
When evaluating a claim, reduce it to:
```text
Because A, therefore B.
```
Then test it with three questions:
1. Does A really cause B?
2. Can B happen without A?
3. Does B matter enough?
This is useful for idea evaluation, writing review, design decisions, and critique.
## Output Patterns
For substantial responses:
```text
Conclusion:
What I did:
What I checked:
Risks / Limits:
Next step:
```
For quick answers:
```text
Conclusion: ...
Why: ...
Next step: ...
```
For decisions:
```text
Recommendation:
Why:
Tradeoff:
Not recommended:
```
## Included Files
```text
SKILL.md
README.md
README.zh-CN.md
examples/
references/
```
- [`SKILL.md`](./SKILL.md): the main executable instructions
- [`references/communication-sop.md`](./references/communication-sop.md): extended communication SOP
- [`references/user-preferences.md`](./references/user-preferences.md): public-facing defaults and tradeoffs
- [`examples/`](./examples): example outputs for common response patterns
## Public Release Notes
This public version removes:
- local absolute paths,
- personal project references,
- private topic traces,
- and source-specific personal study traces.
It keeps only reusable communication rules, neutral examples, and public-facing defaults.

View File

@@ -0,0 +1,208 @@
<div align="center">
<strong>语言</strong><a href="README.md">English</a> | <a href="README.zh-CN.md">中文</a>
</div>
# Expression Skill
一个面向技术工作、写作与编辑、文档、多步骤任务和强验证场景的结论先行表达 skill。
## 简介
`expression-skill` 是一个可复用的沟通技能,用来让助手的回答做到:
- 具体,
- 简洁,
- 可核查,
- 在真实任务压力下仍然有用。
它适合那些用户不想看背景铺垫、而是想直接得到判断、执行路径、可复核总结或明确下一步的场景。
## 设计目标
这个 skill 追求的是:从用户问题到可执行结果之间,走最短且可靠的路径。输出结果通常应落到下面几类之一:
- 一个判断,
- 一个命令,
- 一个文件级总结,
- 一个经过核查的状态更新,
- 或一个可复用产物。
它不追求“看起来很完整”,而是追求降低用户的判断成本、执行成本和复核成本。
## 核心表达模型
一条完整回答至少要让三件事可见:
1. 现在什么是真的,
2. 这件事为什么重要,
3. 接下来应该做什么。
默认优先级是:
1. 结论
2. 证据或理由
3. 风险、不确定性或边界
4. 具体动作
5. 可复用的下一步
## 这个 Skill 强制什么
### 1. 结论先行
先给主判断,不要把它藏在背景和铺垫后面。
### 2. 具体优先于抽象
优先使用:
- 命令,
- 路径,
- 数量,
- 检查结果,
- 例子,
- 可观察行为。
不要停在“看起来正确”的过程词上,除非后面跟着具体动作。
### 3. 只有在会改变结果时才追问
只有当歧义会改变这些内容时,才应该追问:
- 目标是什么,
- 作用对象是什么,
- 完成标准是什么,
- 约束是什么,
- 实现路径会不会不同。
能从文件、配置、文档、命令输出里直接读出来的事实,不应该先问用户。
### 4. 风险尽早说
如果有不确定性、破坏性边界或明显失败风险,要尽早说,不要藏到最后。
### 5. 做减法
删掉不影响判断的背景;合并重复理由;降低低优先级分支;一旦下一步已经清楚,就不要继续铺陈。
## 默认工作流
在回答一个非简单请求前:
1. 先识别用户的实际目的。
2. 只有当歧义会改变结果时才先澄清。
3. 能从环境里读出的事实,先自己读出来。
4. 先形成一句核心判断。
5. 只补充让它可信所必需的支持证据。
6. 尽早说明主要风险或边界。
7. 用最小但有用的下一步收尾。
## 场景规则
### Coding
先说改了什么或应该改什么。带上文件、命令和验证,不要叙述每一步探索过程。
### File Operations
必须说明:
- 输入路径
- 输出路径
- 改了哪些文件
- 哪些文件没改
- 做了什么验证
### Long-Running Work
必须给可见路标:
- step / total
- 已处理多少
- 当前输出路径
- 下一个 checkpoint
- 当前可见 blocker
### Writing and Editing
优先压缩表达,不要膨胀措辞。让贡献、证据和限制一眼可见。
### Technical Discussion
把事实、推断和建议拆开说,尽早暴露薄弱假设。
### Knowledge Work
先说这个知识动作要解决什么问题:决策、证据链、综合整理、可复用方法,还是练习产物。
## 批判与论证框架
当你要判断一个 claim 是否站得住时,先把它压成:
```text
因为 A所以 B。
```
然后用三个问题去测:
1. A 真的会导致 B 吗?
2. 没有 AB 还会发生吗?
3. B 对当前目标真的重要吗?
这套框架适合做 idea 判断、写作审阅、设计决策和批判性分析。
## 输出模板
对于较完整的回复:
```text
结论:
我做了:
我检查了:
风险/限制:
下一步建议:
```
对于简短回答:
```text
结论:...
原因:...
建议:...
```
对于决策建议:
```text
我建议:
理由:
代价:
不建议:
```
## 目录内容
```text
SKILL.md
README.md
README.zh-CN.md
examples/
references/
```
- [`SKILL.md`](./SKILL.md):主技能说明,定义默认行为
- [`references/communication-sop.md`](./references/communication-sop.md):扩展沟通 SOP
- [`references/user-preferences.md`](./references/user-preferences.md):公开版默认偏好与取舍
- [`examples/`](./examples):常见回答模式示例
## 公开版说明
这个公开版已经去除了:
- 本地绝对路径,
- 个人项目引用,
- 私有主题痕迹,
- 特定来源材料的个人学习痕迹。
保留下来的只有可复用的沟通规则、中性示例和公开版默认口径。

View File

@@ -0,0 +1,360 @@
---
name: expression-skill
description: This skill should be used when the user asks for efficient communication, task reports, file-operation summaries, research discussion, study-note synthesis, planning, writing feedback, or responses that need conclusion-first structure, concrete evidence, risk disclosure, and useful next steps.
---
# Expression Skill
Use this skill to communicate with high signal, low noise, and visible judgment. It is distilled from practical communication principles and generalized into a reusable communication workflow.
## Goal
Put the user's current problem at the center. Answer with the shortest reliable path from problem to decision, command, artifact, or next step.
Default priorities:
1. conclusion
2. evidence or reason
3. risk, uncertainty, or boundary
4. concrete action
5. reusable next step
Do not optimize for sounding complete. Optimize for being useful, checkable, and actionable.
## Default Workflow
Before answering a non-trivial request:
1. Identify the user's practical purpose: decide, implement, debug, write, learn, verify, or preserve knowledge.
2. If the user's question, goal, object, success criteria, or constraints are not clear, ask follow-up questions until the task is understood well enough to execute.
3. Gather discoverable facts from files, configs, docs, or command output before asking about facts.
4. Form one core sentence that answers the real problem.
5. Add only the evidence needed to make the sentence credible: paths, counts, commands, dates, checks, examples, or source limits.
6. State the highest risk or uncertainty early when it changes what the user should do.
7. End with the smallest useful next action.
For substantial responses, prefer:
```text
结论:
我做了:
我检查了:
风险/限制:
下一步建议:
```
For quick answers, use:
```text
结论:...
原因:...
建议:...
```
For decisions, use:
```text
我建议:
理由:
代价:
不建议:
```
## Clarification And Question Policy
Ask questions only when the answer changes the outcome.
Before executing a non-trivial task, make sure these are clear:
1. goal: what result the user wants
2. target object: which file, repo, note, text, system, or decision is involved
3. success criteria: what "done" means
4. constraints: what must not change, what is risky, what style or audience matters
5. current state: what is already true or discoverable from the environment
Rules:
- Do not ask for facts that can be discovered from files, configs, docs, or command output.
- Ask in rounds when needed. Prefer 1-3 focused questions per round.
- Ask until the task is understood well enough to execute safely.
- If a safe assumption is enough to move, state it briefly and proceed.
- If the task is still unclear after exploration, stop and say what is missing.
Useful tradeoff questions often choose between:
- speed vs. completeness
- draft vs. final
- local-only vs. public-facing
- preserve source style vs. rewrite aggressively
- exploratory discussion vs. implementation-ready output
## Communication Defaults
- Infer the response language from the user's explicit request or surrounding context. Keep standard technical terms in English when that is clearer.
- Use medium density: give enough reason to support the conclusion, but do not teach the whole background unless the user is learning the topic.
- Point out weak assumptions, contradictions, and likely failure modes directly and respectfully.
- Use direct answers for simple tasks. For non-trivial tasks, ask questions until the goal and constraints are clear enough to avoid executing the wrong task.
- If a safe assumption is enough to move, state it and proceed.
- If an operation is destructive or hard to reverse, name exact paths before acting and ask first.
## Core Rules
### 1. Start With The Core Sentence
Give the main judgment first. Do not begin with long background.
Bad:
```text
我先看了一下这些文件,然后发现里面有一些内容可以合并……
```
Better:
```text
结论:这批文件可以合并成一个主文件,原文件不需要改动。
```
### 2. Serve The User's Purpose
Before writing, ask what problem the answer solves:
- know current state
- decide whether to continue
- find the output path
- confirm what changed and what did not
- reduce risk
- turn material into durable knowledge
- get a concrete next action
Do not merely explain the topic. Connect the answer to the user's current work.
### 3. Prefer Executable Value
Avoid vague phrases such as:
- 系统推进
- 持续优化
- 后续完善
- 建立闭环
- 进一步提升
Replace them with a path, command, checklist, decision, verification step, or concrete next action.
### 4. Sort And Subtract
Rank information when priority matters:
```text
P0必须现在处理
P1建议本轮处理
P2可以之后处理
```
Use subtraction. Say what is not worth doing now when it prevents scope creep.
The user's attention is expensive. Do not make the user extract the point.
Use subtraction actively:
- delete background that does not affect the decision
- merge repeated reasons
- demote low-priority branches
- say what is not worth doing now
- stop once the next useful action is clear
### 5. Make Abstract Claims Concrete
Prefer numbers, paths, commands, timestamps, counts, tests, and examples.
Bad:
```text
结构比较清晰。
```
Better:
```text
这个输出文件有 36 个二级章节、5358 行,开头有索引区,后面按输入顺序整理。
```
Replace big words with observable detail.
Bad:
```text
这个方案需要继续优化。
```
Better:
```text
这个方案还缺两个验证点:运行 `pytest -q`,并回读生成的 CSV 行数。
```
When a sentence feels vague, ask:
- 具体指什么?
- 不用这个词怎么说?
- 你是怎么看出来的?
- 这句话能指导下一步行动吗?
### 6. Ask Fewer, Better Questions
Ask when the answer changes the spec, risk, audience, implementation path, or acceptance criteria.
Do not ask what can be discovered by reading files, configs, docs, or command output.
For planning or ambiguous tasks, ask 1-3 focused questions at a time. Continue asking in rounds until the user's intent is understood. Recommend a default option when possible.
Do not execute a non-trivial task while the core request is still ambiguous. First restate the current understanding and ask what is missing.
### 7. Provide Roadmarks For Long Work
For long jobs, report:
- current step and total steps
- processed amount
- output path so far
- next visible checkpoint
- visible risk or delay
- visible blocker if one appears
### 8. Produce Reusable Artifacts
When useful, convert answers into:
- SOP
- checklist
- template
- command
- structured note
- review questions
- examples
## Scenario Rules
### Coding
Lead with what changed or what should change. Include files, commands, and verification. Do not narrate every exploration step.
### Research Discussion
Separate fact, inference, and recommendation. Surface weak assumptions early. Make the key claim testable.
### Writing And Editing
Prefer compressed claims over inflated wording. Make the contribution, evidence, and limitation visible.
### File Operations
Always report:
- input path
- output path
- changed files
- untouched files
- verification performed
### Long-Running Work
Report roadmarks instead of waiting silently:
- step / total
- processed amount
- output path
- next checkpoint
- visible blocker
### Knowledge Work
State the knowledge problem first: decision, evidence trail, synthesis, reusable method, or practice artifact.
## Critique And Rebuttal
When evaluating an idea, isolate the claim:
```text
Because A, therefore B.
```
Test it with three questions:
1. Does A really cause B?
2. Can B happen without A?
3. Does B matter enough?
Use this for research ideas, writing review, design decisions, and rebuttal-style discussion.
## Common Output Shapes
Status update:
```text
当前状态:
已完成:
未完成:
风险:
下一步:
```
File operation:
```text
输入:
输出:
改动范围:
未改动内容:
验证结果:
```
Learning note:
```text
核心问题:
核心结论:
关键方法:
适用场景:
练习方式:
```
Review or critique:
```text
主要问题:
为什么重要:
建议改法:
验证方式:
```
## Load When Needed
- `references/communication-sop.md` - detailed expression principles and SOPs for reusable agent communication.
- `references/user-preferences.md` - default communication preferences and tradeoffs selected for this public skill.
- `examples/` - short response examples for common work modes.
## Boundaries
- Do not invent facts.
- Mark uncertainty explicitly.
- Do not pretend to understand the user's request. If the request is unclear, ask until the goal, target object, constraints, and success criteria are clear enough to act.
- Do not hide destructive-operation risk.
- Do not over-explain when a command, path, or decision is enough.
- Do not use specialized vocabulary as decoration. Use it only when it improves the current answer.
- For long tasks, keep the user informed with concrete progress.
- For destructive operations, confirm first unless the user explicitly approved the exact deletion.
- For knowledge work, favor durable notes, clear links, and reusable structures.
## Final answer checklist
Before finalizing, check:
- Did I give the conclusion first?
- Did I answer the user's actual purpose?
- Did I distinguish completed work from remaining work?
- Did I include paths/counts/verification when files changed?
- Did I expose risk or uncertainty?
- Did I avoid vague process language?
- Did I give a useful next step?

View File

@@ -0,0 +1,18 @@
# Example: Code Task Report
```text
结论:这个 bug 的根因是配置读取顺序反了,环境变量被默认值覆盖。
我改了:
- `src/config.py`:先读默认值,再用环境变量覆盖。
- `tests/test_config.py`:新增环境变量优先级测试。
我检查了:
- `uv run pytest -q tests/test_config.py` 通过。
风险/限制:
- 我没有跑全量测试;这次改动只覆盖配置模块。
下一步建议:
- 如果要合并,跑一次 `uv run pytest -q` 做全量回归。
```

View File

@@ -0,0 +1,19 @@
# Example: File Operation Report
```text
结论:已把 36 个分散文件合并成一个主文件,原始文件没有改动。
输入:
- `/path/to/source-files/*.md`
输出:
- `/path/to/merged-output.md`
改动范围:
- 新增 1 个合并文件。
- 未修改 36 个原始文件。
验证结果:
- 索引区 36/36。
- 输出文件 5358 行。
```

View File

@@ -0,0 +1,19 @@
# Example: Long-Running Work Update
```text
当前状态:第 2/4 步,正在跑远程 permutation test。
已完成:
- 配置检查完成。
- 远程 tmux window 已启动。
处理中:
- 已运行 38 分钟。
- 当前日志:`temp/trial_perm_1k.log`
风险:
- 目前还没有看到输出 CSV如果 30 分钟后仍无进度,需要检查数据路径或显存。
下一步:
- 下一次 checkpoint 看日志尾部和输出目录文件数。
```

View File

@@ -0,0 +1,14 @@
# Example: Research Discussion
```text
结论:这个 idea 值得保留,但现在不能直接写成 main contribution它更像一个需要额外证据支撑的 mechanism claim。
原因:
- 主张是 "multi-scale augmentation improves small-object detection because it helps the model preserve fine-grained texture cues"。
- 当前最弱的一环是 because还缺少能证明 texture-cue preservation 的机制证据。
建议:
- P0先做 feature-map visualization 或 error-type breakdown验证 small-object recall 的提升来自哪里。
- P1再把 augmentation result 放进 method。
- P2最后再考虑更大的 architecture story不要现在就把 auxiliary module 写成主线。
```

View File

@@ -0,0 +1,17 @@
# Example: Writing Revision Feedback
```text
主要问题:这段话的贡献句太散,读者读完不知道 novelty 在哪里。
为什么重要:
- 现在同时讲了 framework、dataset、analysis 和 generalization。
- 四个点都对,但没有排序,导致最强贡献被稀释。
建议改法:
- 第一句只保留核心贡献。
- 第二句给证据。
- 第三句写限制或边界。
可改成:
"We introduce X, a retrieval-augmented summarization framework that separates evidence selection from response generation. Across three benchmark datasets, X improves factual consistency by Y while preserving summary relevance. The method is designed for long-document NLP settings where source grounding matters more than stylistic compression alone."
```

View File

@@ -0,0 +1,216 @@
# Communication SOP
This reference turns practical communication principles into reusable rules for agent communication.
Source material:
- practical communication notes
- iterative answer-writing practice
## 1. Core Model
Expression is thinking made visible. A useful answer should show:
1. what is true
2. why it matters to the user
3. what should happen next
Do not treat fluency as quality. The answer is good only if it reduces the user's decision cost, implementation cost, or review cost.
## 2. The Two Check Cards
### Check Card 1: Before Speaking
Use this for any non-trivial answer.
1. Motivation: Why does this answer need to be said now?
2. Audience purpose: What does the user want to do with the answer?
3. Framework: What shape will let the user follow the reasoning?
4. Core sentence: If only one sentence survives, what is it?
### Check Card 2: Before Expanding
Use this before writing long explanations.
1. Good question: What problem does the answer solve?
2. Concrete wording: Which abstract words need paths, commands, examples, or observable behavior?
3. Surprise or correction: What likely assumption is wrong or incomplete?
4. Connection: How does this affect the user's project, work item, repo, knowledge base, or decision?
## 3. Default Answer Pipeline
1. Start with the conclusion.
2. Give the minimum evidence needed to trust it.
3. Name risk or uncertainty early.
4. Give a concrete action, path, command, or artifact.
5. Stop when the next step is clear.
If the user is asking for learning or reflection, add:
- core question
- core conclusion
- method or framework
- application scenario
- common mistake
- practice task
## 4. Question Policy
Ask questions only when they change the outcome.
If the user's request is not understood, ask promptly. Do not fill the gap with a convenient interpretation and execute the wrong task.
Before executing a non-trivial task, make sure these are clear:
1. goal: what result the user wants
2. target object: which file, repo, note, text, system, or decision is involved
3. success criteria: what "done" means
4. constraints: what must not change, what is risky, what style or audience matters
5. current state: what is already true or discoverable from the environment
Ask in rounds if needed. Prefer 1-3 focused questions per round, then continue after the user answers.
Good questions choose among meaningful tradeoffs:
- speed vs. completeness
- local-only vs. public-facing
- draft vs. final
- exploratory vs. implementation-ready
- preserve source style vs. rewrite aggressively
Bad questions ask for discoverable facts:
- where a file is
- what a config contains
- which command exists
- whether a dependency is present
Discover those first.
When the task is still unclear after exploration, say:
```text
我现在还不能安全执行,因为 X 不清楚。
我需要确认:
1. ...
2. ...
确认后我再继续。
```
## 5. Concrete Thinking Rules
Replace big words with observable detail.
Bad:
```text
这个方案需要优化闭环。
```
Better:
```text
这个方案缺少两个验证点:运行 `pytest -q`,并回读生成的 CSV 行数。
```
Use these prompts when a sentence feels vague:
- 具体指什么?
- 不用这个词怎么说?
- 你是怎么看出来的?
- 这句话能指导下一步行动吗?
## 6. Core Sentence And Subtraction
The user's attention is expensive. Do not make the user extract the point.
Use subtraction:
- delete background that does not affect the decision
- merge repeated reasons
- demote low-priority branches
- say what is not worth doing now
For code and file tasks, the core sentence should often include the exact affected path or command.
## 7. Frameworks To Reuse
Use frameworks only when they reduce cognitive load.
- Conclusion-first: best for direct answers and reports.
- Pyramid: conclusion, then 2-3 reasons.
- Past-present-future: good for progress reports and retrospectives.
- Sky-rain-umbrella: background, problem, solution.
- 3C: common view, competing view, my view.
- Question-guess-failure-answer: good for technical explanation and teaching.
- Role-challenge: good for making abstract knowledge relevant.
## 8. Critique And Rebuttal
When evaluating an idea, identify the claim:
```text
Because A, therefore B.
```
Test it with three questions:
1. Does A really cause B?
2. Can B happen without A?
3. Does B matter enough?
When strengthening an idea, reverse the tests:
1. A often causes B.
2. Without A, B is unlikely or impossible.
3. B matters to the user's goal.
Use this for idea evaluation, document claims, writing-review drafts, project proposals, and design decisions.
## 9. Scenario Rules
### Coding
Lead with what changed or what should change. Include files, commands, and verification. Do not narrate every exploration step.
### Research discussion
Separate fact, inference, and recommendation. Surface weak assumptions early.
### Writing and editing
Prefer compressed, reader-facing claims. Avoid inflated wording. Make the contribution, evidence, and limitation visible.
### Knowledge work
State the knowledge problem first: decision, evidence trail, synthesis, reusable method, or practice artifact.
### Long-running work
Report roadmarks:
- step / total
- processed amount
- output path
- next checkpoint
- visible blocker
### File operations
Always report:
- input path
- output path
- changed files
- untouched files
- verification performed
## 10. Common Mistakes To Avoid
- Teaching the whole background when the user needs a decision.
- Asking a question before reading discoverable files.
- Using abstract verbs without a concrete action.
- Reporting "done" without verification.
- Hiding uncertainty until the end.
- Giving too many options without a recommendation.
- Treating user criticism as conflict instead of useful signal.

View File

@@ -0,0 +1,53 @@
# Communication Preferences
These defaults were selected during the public `expression-skill` redesign.
## Communication Defaults
- Default language: infer from the user's explicit request or the surrounding context.
- Keep standard technical terms in English when clearer.
- Detail level: medium explanation density.
- Challenge style: point out problems directly, then give cost and alternative.
- Question style: direct answer plus key questions.
- If the user's question is not understood, ask promptly and keep asking in focused rounds until the goal, target object, constraints, and success criteria are clear.
## Practical Defaults
- For simple tasks, answer directly.
- For non-trivial work, give the conclusion or short plan first, then ask 1-3 questions only if they materially change the result.
- Do not execute ambiguous non-trivial tasks from a guessed interpretation. Gather enough information first, then act.
- Prefer executable paths, commands, file paths, checklists, templates, and verification steps.
- Default to source-preserving, scoped edits for file work.
- State destructive-operation boundaries before acting.
## Preferred Final Report Shape
```text
结论:
我做了:
我检查了:
风险/限制:
下一步建议:
```
Use this shape when it helps. Do not force it onto tiny answers.
## Preferred Tone
- Direct.
- Concrete.
- Respectful.
- No motivational filler.
- No vague "optimize/align/close loop" wording unless tied to a concrete action.
## Reusable Context Reminder
This skill is especially useful for:
- technical work
- writing and editing
- documentation
- multi-step tasks
- verification-heavy tasks
Frame advice around the user's current work rather than generic public-speaking theory.

View File

@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,43 @@
---
name: frontend-design
description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
license: Complete terms in LICENSE.txt
version: 0.1.0
---
This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices.
The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints.
## Design Thinking
Before coding, understand the context and commit to a BOLD aesthetic direction:
- **Purpose**: What problem does this interface solve? Who uses it?
- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction.
- **Constraints**: Technical requirements (framework, performance, accessibility).
- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember?
**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity.
Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is:
- Production-grade and functional
- Visually striking and memorable
- Cohesive with a clear aesthetic point-of-view
- Meticulously refined in every detail
## Frontend Aesthetics Guidelines
Focus on:
- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font.
- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes.
- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise.
- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays.
NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character.
Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations.
**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well.
Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision.

View File

@@ -0,0 +1,477 @@
---
name: git-workflow
description: This skill should be used when the user asks to "create git commit", "manage branches", "follow git workflow", "use Conventional Commits", "handle merge conflicts", or asks about git branching strategies, version control best practices, pull request workflows. Provides comprehensive Git workflow guidance for team collaboration.
version: 1.2.0
---
# Git Workflow Standards
This document defines the project's Git usage standards, including commit message format, branch management strategy, workflows, merge strategies, and more. Following these standards improves collaboration efficiency, enables traceability, supports automation, and reduces conflicts.
## Commit Message Standards
The project follows the **Conventional Commits** specification:
```
<type>(<scope>): <subject>
<body>
<footer>
```
### Type Reference
| Type | Description | Example |
| :--- | :--- | :--- |
| `feat` | New feature | `feat(user): add user export functionality` |
| `fix` | Bug fix | `fix(login): fix captcha not refreshing` |
| `docs` | Documentation update | `docs(api): update API documentation` |
| `refactor` | Refactoring | `refactor(utils): refactor utility functions` |
| `perf` | Performance improvement | `perf(list): optimize list performance` |
| `test` | Test related | `test(user): add unit tests` |
| `chore` | Other changes | `chore: update dependency versions` |
### Subject Rules
- Start with a verb: add, fix, update, remove, optimize
- No more than 50 characters
- No period at the end
For more detailed conventions and examples, see `references/commit-conventions.md`.
## Branch Management Strategy
### Branch Types
| Branch Type | Naming Convention | Description | Lifecycle |
| :--- | :--- | :--- | :--- |
| master | `master` | Main branch, releasable state | Permanent |
| develop | `develop` | Development branch, latest integrated code | Permanent |
| feature | `feature/feature-name` | Feature branch | Delete after completion |
| bugfix | `bugfix/issue-description` | Bug fix branch | Delete after fix |
| hotfix | `hotfix/issue-description` | Emergency fix branch | Delete after fix |
| release | `release/version-number` | Release branch | Delete after release |
### Branch Naming Examples
```
feature/user-management # User management feature
feature/123-add-export # Issue-linked feature
bugfix/login-error # Login error fix
hotfix/security-vulnerability # Security vulnerability fix
release/v1.0.0 # Version release
```
### Branch Protection Rules
**master branch:**
- No direct pushes allowed
- Must merge via Pull Request
- Must pass CI checks
- Requires at least one Code Review approval
**develop branch:**
- Direct pushes restricted
- Pull Request merges recommended
- Must pass CI checks
For detailed branch strategies and workflows, see `references/branching-strategies.md`.
## Workflows
### Daily Development Workflow
```bash
# 1. Sync latest code
git checkout develop
git pull origin develop
# 2. Create feature branch
git checkout -b feature/user-management
# 3. Develop and commit
git add .
git commit -m "feat(user): add user list page"
# 4. Push to remote
git push -u origin feature/user-management
# 5. Create Pull Request and request Code Review
# 6. Merge to develop (via PR)
# 7. Delete feature branch
git branch -d feature/user-management
git push origin -d feature/user-management
```
### Hotfix Workflow
```bash
# 1. Create fix branch from master
git checkout master
git pull origin master
git checkout -b hotfix/critical-bug
# 2. Fix and commit
git add .
git commit -m "fix(auth): fix authentication bypass vulnerability"
# 3. Merge to master
git checkout master
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1 -m "hotfix: fix authentication bypass vulnerability"
git push origin master --tags
# 4. Sync to develop
git checkout develop
git merge --no-ff hotfix/critical-bug
git push origin develop
```
### Release Workflow
```bash
# 1. Create release branch
git checkout develop
git checkout -b release/v1.0.0
# 2. Update version numbers and documentation
# 3. Commit version update
git add .
git commit -m "chore(release): prepare release v1.0.0"
# 4. Merge to master
git checkout master
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "release: v1.0.0 official release"
git push origin master --tags
# 5. Sync to develop
git checkout develop
git merge --no-ff release/v1.0.0
git push origin develop
```
## Merge Strategy
### Merge vs Rebase
| Feature | Merge | Rebase |
| :--- | :--- | :--- |
| History | Preserves complete history | Linear history |
| Use case | Public branches | Private branches |
| Recommended for | Merging to main branch | Syncing upstream code |
### Recommendations
- **Feature branch syncing develop**: Use `rebase`
- **Feature branch merging to develop**: Use `merge --no-ff`
- **develop merging to master**: Use `merge --no-ff`
```bash
# ✅ Recommended: Feature branch syncing develop
git checkout feature/user-management
git rebase develop
# ✅ Recommended: Merge feature branch to develop
git checkout develop
git merge --no-ff feature/user-management
# ❌ Not recommended: Rebase on public branch
git checkout develop
git rebase feature/xxx # Dangerous operation
```
**Project convention**: Use `--no-ff` when merging feature branches to preserve branch history.
For detailed merge strategies and techniques, see `references/merge-strategies.md`.
## Conflict Resolution
### Identifying Conflicts
```
<<<<<<< HEAD
// Current branch code
const name = 'Alice'
=======
// Branch being merged
const name = 'Bob'
>>>>>>> feature/user-management
```
### Resolving Conflicts
```bash
# 1. View conflicting files
git status
# 2. Manually edit files to resolve conflicts
# 3. Mark as resolved
git add <file>
# 4. Complete the merge
git commit # merge conflict
# or
git rebase --continue # rebase conflict
```
### Conflict Resolution Strategies
```bash
# Keep current branch version
git checkout --ours <file>
# Keep incoming branch version
git checkout --theirs <file>
# Abort merge
git merge --abort
git rebase --abort
```
### Preventing Conflicts
1. **Sync code regularly** - Pull latest code before starting work each day
2. **Small commits** - Commit small changes frequently
3. **Modular features** - Implement different features in different files
4. **Communication** - Avoid modifying the same file simultaneously
For detailed conflict handling and advanced techniques, see `references/conflict-resolution.md`.
## .gitignore Standards
### Basic Rules
```
# Ignore all .log files
*.log
# Ignore directories
node_modules/
# Ignore directory at root
/temp/
# Ignore files in all directories
**/.env
# Don't ignore specific files
!.gitkeep
```
### Common .gitignore
```
node_modules/
dist/
build/
.idea/
.vscode/
.env
.env.local
logs/
*.log
.DS_Store
Thumbs.db
```
For detailed .gitignore patterns and project-specific configurations, see `references/gitignore-guide.md`.
## Tag Management
Uses **Semantic Versioning**:
```
MAJOR.MINOR.PATCH[-PRERELEASE]
```
### Version Change Rules
- **MAJOR**: Incompatible API changes (v1.0.0 → v2.0.0)
- **MINOR**: Backward-compatible new features (v1.0.0 → v1.1.0)
- **PATCH**: Backward-compatible bug fixes (v1.0.0 → v1.0.1)
### Tag Operations
```bash
# Create annotated tag (recommended)
git tag -a v1.0.0 -m "release: v1.0.0 official release"
# Push tags
git push origin v1.0.0
git push origin --tags
# View tags
git tag
git show v1.0.0
# Delete tag
git tag -d v1.0.0
git push origin :refs/tags/v1.0.0
```
## Team Collaboration Standards
### Pull Request Standards
PRs should include:
```markdown
## Change Description
<!-- Describe the content and purpose of this change -->
## Change Type
- [ ] New feature (feat)
- [ ] Bug fix (fix)
- [ ] Code refactoring (refactor)
## Testing Method
<!-- Describe how to test -->
## Related Issue
Closes #xxx
## Checklist
- [ ] Code has been self-tested
- [ ] Documentation has been updated
```
### Code Review Standards
Review focus areas:
- **Code quality**: Clear and readable, proper naming, no duplicate code
- **Logic correctness**: Business logic correct, edge cases handled
- **Security**: No security vulnerabilities, sensitive information protected
- **Performance**: No obvious performance issues, resources properly released
For detailed collaboration standards and best practices, see `references/collaboration.md`.
## Common Issues
### Amending the Last Commit
```bash
# Amend commit content (not yet pushed)
git add forgotten-file.ts
git commit --amend --no-edit
# Amend commit message
git commit --amend -m "new commit message"
```
### Push Rejected
```bash
# Pull then push
git pull origin master
git push origin master
# Use rebase for cleaner history
git pull --rebase origin master
git push origin master
```
### Rollback to Previous Version
```bash
# Reset to specific commit (discards subsequent commits)
git reset --hard abc123
# Create reverse commit (recommended, preserves history)
git revert abc123
```
### Stash Current Work
```bash
git stash save "work in progress"
git stash list
git stash pop
```
### View File Modification History
```bash
git log -- <file> # Commit history
git log -p -- <file> # Detailed content
git blame <file> # Per-line author
```
## Best Practices Summary
### Commit Standards
**Recommended**:
- Follow Conventional Commits specification
- Write clear commit messages describing changes
- One commit for one logical change
- Run code checks before committing
**Prohibited**:
- Vague commit messages
- Multiple unrelated changes in one commit
- Committing sensitive information (passwords, keys)
- Developing directly on main branch
### Branch Management
**Recommended**:
- Use feature branches for development
- Regularly sync main branch code
- Delete branches promptly after feature completion
- Use `--no-ff` merge to preserve history
**Prohibited**:
- Developing directly on main branch
- Long-lived unmerged feature branches
- Non-standard branch naming
- Rebasing on public branches
### Code Review
**Recommended**:
- All code goes through Pull Requests
- At least one reviewer approval before merging
- Provide constructive feedback
**Prohibited**:
- Merging without review
- Reviewing your own code
## Additional Resources
### Reference Files
For detailed guidance on specific topics:
- **`references/commit-conventions.md`** - Commit message detailed conventions and examples
- **`references/branching-strategies.md`** - Comprehensive branch management strategies
- **`references/merge-strategies.md`** - Merge, rebase, and conflict resolution strategies
- **`references/conflict-resolution.md`** - Detailed conflict handling and prevention
- **`references/advanced-usage.md`** - Git performance optimization, security, submodules, and advanced techniques
- **`references/collaboration.md`** - Pull request and code review guidelines
- **`references/gitignore-guide.md`** - .gitignore patterns and project-specific configurations
### Example Files
Working examples in `examples/`:
- **`examples/commit-messages.txt`** - Good commit message examples
- **`examples/workflow-commands.sh`** - Common workflow command snippets
## Summary
This document defines the project's Git standards:
1. **Commit Messages** - Follow Conventional Commits specification
2. **Branch Management** - master/develop/feature/bugfix/hotfix/release branch strategy
3. **Workflows** - Standard processes for daily development, hotfixes, and releases
4. **Merge Strategy** - Use rebase to sync feature branches, merge --no-ff to merge
5. **Tag Management** - Semantic versioning, annotated tags
6. **Conflict Resolution** - Regular syncing, small commits, team communication
Following these standards improves collaboration efficiency, ensures code quality, and simplifies version management.

View File

@@ -0,0 +1,50 @@
# 好的 Commit Message 示例
## 简单提交
feat(user): 添加用户导出功能
fix(login): 修复验证码不刷新问题
docs(readme): 更新安装说明
## 带 Body 的提交
feat(user): 添加用户批量导入功能
- 支持 Excel 文件导入
- 支持数据校验和错误提示
- 支持导入进度显示
相关需求: #123
fix(login): 修复验证码不刷新问题
原因: 缓存时间设置过长导致验证码一直显示同一张图片
方案: 将缓存时间从5分钟调整为1分钟
## 带 Footer 的提交
feat(api): 重构用户接口
BREAKING CHANGE: 用户查询接口路径变更
旧路径: /api/user/list
新路径: /api/system/user/list
Closes #789
## 特殊类型提交
revert: 回滚 feat(user)
回滚提交 abc123因为引入了性能问题
chore(release): 准备发布 v1.0.0
- 更新版本号到 1.0.0
- 更新 CHANGELOG.md
- 更新 README.md
test(user): 添加用户模块单元测试
覆盖用户注册、登录、资料修改功能

View File

@@ -0,0 +1,132 @@
#!/bin/bash
# Git 工作流常用命令示例
# ============================================
# 日常开发流程
# ============================================
# 1. 同步最新代码
git checkout develop
git pull origin develop
# 2. 创建功能分支
git checkout -b feature/user-management
# 3. 开发并提交
git add .
git commit -m "feat(user): 添加用户列表页面"
# 4. 推送到远程
git push -u origin feature/user-management
# 5. 同步上游更新到功能分支
git fetch origin develop
git rebase origin/develop
# 6. 合并到 develop通过 PR 或直接)
git checkout develop
git merge --no-ff feature/user-management
git push origin develop
# 7. 删除功能分支
git branch -d feature/user-management
git push origin -d feature/user-management
# ============================================
# 紧急修复流程
# ============================================
# 1. 从 master 创建修复分支
git checkout master
git pull origin master
git checkout -b hotfix/security-fix
# 2. 修复并提交
git add .
git commit -m "fix(auth): 修复认证绕过漏洞"
# 3. 合并到 master
git checkout master
git merge --no-ff hotfix/security-fix
git tag -a v1.0.1 -m "hotfix: 修复认证绕过漏洞"
git push origin master --tags
# 4. 同步到 develop
git checkout develop
git merge --no-ff hotfix/security-fix
git push origin develop
# 5. 删除修复分支
git branch -d hotfix/security-fix
# ============================================
# 版本发布流程
# ============================================
# 1. 创建发布分支
git checkout develop
git checkout -b release/v1.0.0
# 2. 更新版本号和文档
# 手动编辑 package.json、CHANGELOG.md 等
# 3. 提交版本更新
git add .
git commit -m "chore(release): 准备发布 v1.0.0"
# 4. 合并到 master
git checkout master
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "release: v1.0.0 正式版本"
git push origin master --tags
# 5. 同步到 develop
git checkout develop
git merge --no-ff release/v1.0.0
git push origin develop
# 6. 删除发布分支
git branch -d release/v1.0.0
# ============================================
# 冲突处理
# ============================================
# Merge 冲突处理
git merge feature/xxx
# 编辑冲突文件...
git add <file>
git commit
# Rebase 冲突处理
git rebase develop
# 编辑冲突文件...
git add <file>
git rebase --continue
# 放弃合并
git merge --abort
git rebase --abort
# ============================================
# 常用工具命令
# ============================================
# 查看状态
git status
# 查看日志
git log --oneline --graph --all
# 查看分支
git branch -a
# 暂存工作
git stash save "工作进行中"
git stash list
git stash pop
# 查看文件修改
git diff
git diff --staged
git log -p -- <file>

View File

@@ -0,0 +1,393 @@
# Git 高级用法
## 标签管理
### 版本号规范
采用 **语义化版本**Semantic Versioning
```
主版本号.次版本号.修订号[-预发布标识]
MAJOR.MINOR.PATCH[-PRERELEASE]
```
| 版本变化 | 说明 | 示例 |
| :------- | :----------------- | :---------------- |
| 主版本号 | 不兼容的 API 修改 | `v1.0.0 → v2.0.0` |
| 次版本号 | 向下兼容的功能新增 | `v1.0.0 → v1.1.0` |
| 修订号 | 向下兼容的问题修正 | `v1.0.0 → v1.0.1` |
### 预发布标识
- `alpha` - 内测版本
- `beta` - 公测版本
- `rc` - 候选版本
```
v1.0.0-alpha.1 # 第一个内测版本
v1.0.0-beta.1 # 第一个公测版本
v1.0.0-rc.1 # 第一个候选版本
v1.0.0 # 正式版本
```
### 标签操作
#### 创建附注标签(推荐)
```bash
git tag -a v1.0.0 -m "release: v1.0.0 正式版本
主要更新:
- 新增用户管理模块
- 新增支付功能
- 优化查询性能"
```
#### 推送标签
```bash
# 推送单个标签
git push origin v1.0.0
# 推送所有标签
git push origin --tags
```
#### 查看标签
```bash
git tag
git tag -l "v1.*"
git show v1.0.0
```
#### 删除标签
```bash
# 删除本地标签
git tag -d v1.0.0
# 删除远程标签
git push origin :refs/tags/v1.0.0
```
## Git 性能优化
### 大型仓库优化
```bash
# 浅克隆(只获取最近的提交)
git clone --depth 1 https://github.com/repo/project.git
# 部分克隆(按需获取)
git clone --filter=blob:none https://github.com/repo/project.git
# 稀疏检出(只检出需要的目录)
git clone --filter=blob:none --sparse https://github.com/repo/project.git
cd project
git sparse-checkout init --cone
git sparse-checkout set src/frontend
```
### 清理仓库
```bash
# 查看仓库大小
git count-objects -vH
# 清理无用对象
git gc --aggressive --prune=now
# 清理远程已删除的分支引用
git remote prune origin
# 清理本地已合并的分支
git branch --merged master | grep -v "\\*\\|master\\|develop" | xargs -n 1 git branch -d
```
### 提升操作速度
```bash
# 启用文件系统缓存
git config --global core.fscache true
# 启用并行获取
git config --global fetch.parallel 4
# 启用未跟踪文件缓存
git config --global core.untrackedCache true
```
## Git 安全规范
### 敏感信息保护
```bash
# 检查历史提交中的敏感信息
git log -p | grep -E "(password|secret|api_key)"
# 从历史记录中删除敏感文件
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch config/secrets.yml' \
--prune-empty --tag-name-filter cat -- --all
# 使用 git-secrets 预防敏感信息提交
git secrets --install
git secrets --register-aws
```
### 签名验证
```bash
# 配置 GPG 签名
git config --global user.signingkey YOUR_KEY_ID
git config --global commit.gpgsign true
# 创建签名提交
git commit -S -m "feat: 签名提交"
# 验证签名
git log --show-signature
```
### 仓库权限控制
| 规则 | master | develop | feature/* |
| :--------------- | :----- | :------ | :-------- |
| 禁止强制推送 | ✅ | ✅ | ❌ |
| 禁止删除 | ✅ | ✅ | ❌ |
| 必须 Code Review | ✅ | ✅ | ❌ |
| 必须通过 CI | ✅ | ✅ | ❌ |
| 必须签名提交 | ✅ | ❌ | ❌ |
## 子模块管理
### 添加子模块
```bash
git submodule add https://github.com/user/repo.git libs/repo
# 克隆包含子模块的项目
git clone --recurse-submodules https://github.com/user/project.git
# 初始化已有项目的子模块
git submodule init
git submodule update
```
### 更新子模块
```bash
# 更新单个子模块
cd libs/repo
git pull origin main
# 更新所有子模块
git submodule update --remote
# 提交子模块更新
cd ..
git add libs/repo
git commit -m "chore: 更新子模块版本"
```
### 删除子模块
```bash
# 删除子模块条目
git submodule deinit -f libs/repo
# 删除 .git/modules 中的缓存
rm -rf .git/modules/libs/repo
# 删除子模块目录
git rm -f libs/repo
```
## 常见问题解决
### 1. 修改最后一次提交
```bash
# 修改提交内容(未推送)
git add forgotten-file.ts
git commit --amend --no-edit
# 修改提交消息
git commit --amend -m "新的提交消息"
# 回滚最后一次提交,保留更改
git reset --soft HEAD~1
```
### 2. 推送被拒绝
```bash
# 先拉取再推送
git pull origin master
git push origin master
# 使用 rebase 保持历史清晰
git pull --rebase origin master
git push origin master
```
### 3. 回滚到之前版本
```bash
# 重置到指定提交(丢弃之后的提交)
git reset --hard abc123
# 创建反向提交(推荐,保留历史)
git revert abc123
```
### 4. 恢复误删的分支
```bash
# 查看操作历史
git reflog
# 恢复分支
git checkout -b feature/xxx def456
```
### 5. 合并多个提交
```bash
# 交互式 rebase只能合并未推送的提交
git rebase -i HEAD~5
# 在编辑器中将要合并的提交标记为 squash
```
### 6. 暂存当前工作
```bash
git stash save "工作进行中"
git stash list
git stash pop
git stash apply stash@{0}
```
### 7. 查看文件修改历史
```bash
git log -- <file> # 提交历史
git log -p -- <file> # 详细内容
git blame <file> # 每行修改人
```
### 8. 处理大文件
```bash
# 使用 Git LFS
git lfs install
git lfs track "*.zip"
git add .gitattributes
```
## 实用技巧
### 配置别名
```bash
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.lg "log --graph --oneline --all"
```
### 美化日志
```bash
# 图形化历史
git log --graph --oneline --all
# 搜索提交消息
git log --grep="用户管理"
# 搜索代码变更
git log -S"function_name"
```
### 快速操作
```bash
# 放弃所有未提交更改
git reset --hard HEAD
# 放弃某个文件更改
git checkout -- filename
# 删除未跟踪文件
git clean -fd
# 批量删除已合并分支
git branch --merged master | grep -v "\* master" | xargs -n 1 git branch -d
```
### 安全操作
```bash
# 查看将要推送的内容
git push --dry-run
# 安全的强制推送
git push --force-with-lease
# 备份分支
git branch backup-master master
```
### 查找问题提交
```bash
# 二分查找引入Bug的提交
git bisect start
git bisect bad # 标记当前有问题
git bisect good v1.0.0 # 标记某版本是好的
# Git会自动切换提交测试后标记 good/bad
git bisect reset # 结束查找
```
## CHANGELOG 管理
### 自动生成 CHANGELOG
使用 `conventional-changelog` 自动生成:
```bash
# 安装
pnpm install -D conventional-changelog-cli
# 生成 CHANGELOG
npx conventional-changelog -p angular -i CHANGELOG.md -s
```
### CHANGELOG 格式
```markdown
# 更新日志
## [1.2.0] - 2024-01-15
### 新增
- 新增用户导出功能 (#123)
- 新增数据备份模块
### 修复
- 修复登录验证码不刷新问题 (#456)
- 修复列表分页异常
### 变更
- 优化用户查询性能
- 调整菜单权限校验逻辑
### 移除
- 移除废弃的API接口
## [1.1.0] - 2024-01-01
...
```

View File

@@ -0,0 +1,175 @@
# 分支管理策略详解
## 分支类型
| 分支类型 | 命名规范 | 说明 | 生命周期 |
| :------- | :---------------- | :------------------------- | :------------- |
| master | `master` | 主分支,始终保持可发布状态 | 永久 |
| develop | `develop` | 开发分支,集成最新开发代码 | 永久 |
| feature | `feature/功能名` | 功能分支 | 开发完成后删除 |
| bugfix | `bugfix/问题描述` | Bug修复分支 | 修复完成后删除 |
| hotfix | `hotfix/问题描述` | 紧急修复分支 | 修复完成后删除 |
| release | `release/版本号` | 发布分支 | 发布完成后删除 |
## 分支命名规范
### 功能分支
```
feature/user-management # ✅ 用户管理功能
feature/123-add-export # ✅ 关联Issue的功能
```
### Bug修复分支
```
bugfix/login-error # ✅ 登录错误修复
bugfix/456-fix-timeout # ✅ 关联Issue的修复
```
### 紧急修复分支
```
hotfix/security-vulnerability # ✅ 安全漏洞修复
hotfix/v1.0.1 # ✅ 版本号修复
```
### 发布分支
```
release/v1.0.0 # ✅ 版本发布
release/v2.0.0-beta.1 # ✅ 预发布版本
```
## 分支保护规则
### master 分支
- 禁止直接推送
- 必须通过 Pull Request 合并
- 必须通过 CI 检查
- 必须至少一人 Code Review
### develop 分支
- 限制直接推送
- 建议通过 Pull Request 合并
- 必须通过 CI 检查
## 分支操作命令
### 创建功能分支
```bash
git checkout develop
git pull origin develop
git checkout -b feature/user-management
```
### 创建Bug修复分支
```bash
git checkout develop
git pull origin develop
git checkout -b bugfix/login-error
```
### 创建紧急修复分支从master创建
```bash
git checkout master
git pull origin master
git checkout -b hotfix/security-fix
```
### 删除分支
```bash
git branch -d feature/user-management # 删除本地分支
git push origin -d feature/user-management # 删除远程分支
```
## 工作流程详解
### 日常开发流程
```bash
# 1. 同步最新代码
git checkout develop
git pull origin develop
# 2. 创建功能分支
git checkout -b feature/user-management
# 3. 开发并提交
git add .
git commit -m "feat(user): 添加用户列表页面"
# 4. 推送到远程
git push -u origin feature/user-management
# 5. 创建 Pull Request 并请求 Code Review
# 6. 合并到 develop通过 PR
# 7. 删除功能分支
git branch -d feature/user-management
git push origin -d feature/user-management
```
### 紧急修复流程
```bash
# 1. 从 master 创建修复分支
git checkout master
git pull origin master
git checkout -b hotfix/critical-bug
# 2. 修复并提交
git add .
git commit -m "fix(auth): 修复认证绕过漏洞"
# 3. 合并到 master
git checkout master
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1 -m "hotfix: 修复认证绕过漏洞"
git push origin master --tags
# 4. 同步到 develop
git checkout develop
git merge --no-ff hotfix/critical-bug
git push origin develop
# 5. 删除修复分支
git branch -d hotfix/critical-bug
```
### 版本发布流程
```bash
# 1. 创建发布分支
git checkout develop
git checkout -b release/v1.0.0
# 2. 更新版本号和文档
# 修改 package.json 版本号
# 更新 CHANGELOG.md
# 3. 提交版本更新
git add .
git commit -m "chore(release): 准备发布 v1.0.0"
# 4. 合并到 master
git checkout master
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "release: v1.0.0 正式版本"
git push origin master --tags
# 5. 同步到 develop
git checkout develop
git merge --no-ff release/v1.0.0
git push origin develop
# 6. 删除发布分支
git branch -d release/v1.0.0
```

View File

@@ -0,0 +1,119 @@
# 多人协作规范
## Pull Request 规范
创建 PR 时应包含以下内容:
```markdown
## 变更说明
<!-- 描述本次变更的内容和目的 -->
## 变更类型
- [ ] 新功能 (feat)
- [ ] Bug 修复 (fix)
- [ ] 代码重构 (refactor)
- [ ] 文档更新 (docs)
- [ ] 其他
## 测试方式
<!-- 描述如何测试这些变更 -->
## 关联 Issue
Closes #xxx
## 检查清单
- [ ] 代码已自测
- [ ] 文档已更新
- [ ] 变更已添加到 CHANGELOG
```
## Code Review 规范
### 审查要点
#### 1. 代码质量
- 代码是否清晰易读
- 命名是否规范
- 是否有重复代码
#### 2. 逻辑正确性
- 业务逻辑是否正确
- 边界条件是否处理
- 异常情况是否考虑
#### 3. 安全性
- 是否有安全漏洞
- 敏感信息是否暴露
- 输入是否校验
#### 4. 性能
- 是否有性能问题
- 资源是否正确释放
- 算法复杂度是否合理
### 反馈格式
```markdown
<!-- 必须修改 -->
🔴 **必须修改**: 这里有 SQL 注入风险,需要使用参数化查询
<!-- 建议修改 -->
🟡 **建议修改**: 这个方法可以提取为工具函数,提高复用性
<!-- 讨论 -->
💬 **讨论**: 这里是否可以考虑使用缓存?
<!-- 赞 -->
👍 **赞**: 这个封装很优雅!
```
## 最佳实践总结
### 提交规范
**推荐:**
- 使用 Conventional Commits 规范
- 提交消息清晰描述改动
- 一次提交只做一件事
- 提交前进行代码检查
**禁止:**
- 提交消息模糊不清
- 一次提交多个不相关改动
- 提交敏感信息(密码、密钥)
- 直接在主分支开发
### 分支管理
**推荐:**
- 使用 feature 分支开发
- 定期同步主分支代码
- 功能完成后及时删除分支
- 使用 `--no-ff` 合并保留历史
**禁止:**
- 在主分支直接开发
- 长期不合并的功能分支
- 分支命名不规范
- 在公共分支上 rebase
### 代码审查
**推荐:**
- 所有代码通过 Pull Request
- 至少一人审核通过才能合并
- 提供建设性反馈
**禁止:**
- 未经审查直接合并
- 自己审查自己的代码

View File

@@ -0,0 +1,128 @@
# Commit Message 详细规范
## Conventional Commits 格式
采用 **Conventional Commits** 规范,提交消息格式如下:
```
<type>(<scope>): <subject>
<body>
<footer>
```
## 字段说明
| 字段 | 必填 | 说明 |
| :------ | :--- | :------- |
| type | ✅ | 提交类型 |
| scope | ❌ | 影响范围 |
| subject | ✅ | 简短描述 |
| body | ❌ | 详细描述 |
| footer | ❌ | 脚注信息 |
## Type 类型
| 类型 | 说明 | 示例 |
| :--------- | :------- | :---------------------------------- |
| `feat` | 新功能 | `feat(user): 新增用户导出功能` |
| `fix` | 修复Bug | `fix(login): 修复验证码不刷新问题` |
| `docs` | 文档更新 | `docs(api): 更新接口文档` |
| `style` | 代码格式 | `style: 调整代码缩进` |
| `refactor` | 重构 | `refactor(utils): 重构日期工具函数` |
| `perf` | 性能优化 | `perf(list): 优化列表渲染性能` |
| `test` | 测试相关 | `test(user): 添加用户模块单元测试` |
| `build` | 构建相关 | `build: 升级 vite 到 5.0` |
| `ci` | CI配置 | `ci: 添加 GitHub Actions` |
| `chore` | 其他修改 | `chore: 更新依赖版本` |
| `revert` | 回滚提交 | `revert: 回滚 feat(user)` |
## Scope 范围
Scope 用于说明提交影响的范围,常用的 scope 包括:
- `data` - 数据处理
- `utils` - 工具函数
- `model` - 模型架构
- `config` - 参数配置
- `trainer` - 训练
- `evaluator` - 测评
- `workflow` - 工作流
## Subject 规范
- 使用动词开头:添加、修复、更新、移除、优化
- 不超过50个字符
- 不以句号结尾
- 使用中文或英文,保持一致
### 正确与错误示例
```
# ✅ 正确示例
feat(user): 添加用户导出功能
fix(login): 修复验证码不刷新问题
# ❌ 错误示例
feat(user): 添加用户导出功能。 # 不要句号
feat(user): 用户导出 # 要用动词开头
feat: 添加了一个新的用户导出功能 # 太长
```
## Body 详细描述
当改动较大或需要说明原因时,使用 Body 提供详细描述:
```
feat(user): 添加用户批量导入功能
- 支持 Excel 文件导入
- 支持数据校验和错误提示
- 支持导入进度显示
相关需求: #123
```
## Footer 脚注
用于关联 Issue 或说明破坏性变更:
```
# 关联 Issue
Closes #123, #456
# 破坏性变更
BREAKING CHANGE: 用户接口返回格式变更
旧格式: { data: user }
新格式: { code: 200, data: user, msg: 'success' }
```
## 完整示例
### 简单提交
```bash
git commit -m "feat(user): 添加用户导出功能"
```
### 带 Body 的提交
```bash
git commit -m "fix(login): 修复验证码不刷新问题
原因: 缓存时间设置过长导致验证码一直显示同一张图片
方案: 将缓存时间从5分钟调整为1分钟"
```
### 带 Footer 的提交
```bash
git commit -m "feat(api): 重构用户接口
BREAKING CHANGE: 用户查询接口路径变更
旧路径: /api/user/list
新路径: /api/system/user/list
Closes #789"
```

View File

@@ -0,0 +1,148 @@
# 冲突处理详解
## 识别冲突
当 Git 无法自动合并时,会标记冲突:
```
<<<<<<< HEAD
// 当前分支的代码
const name = '张三'
=======
// 要合并的分支的代码
const name = '李四'
>>>>>>> feature/user-management
```
## 解决冲突步骤
### 1. 查看冲突文件
```bash
git status
```
### 2. 手动编辑文件,解决冲突
打开冲突文件,找到冲突标记(`<<<<<<<``=======``>>>>>>>`),手动编辑选择保留的内容或合并两者。
### 3. 标记已解决
```bash
git add <file>
```
### 4. 完成合并
```bash
# 对于 merge 冲突
git commit
# 对于 rebase 冲突
git rebase --continue
```
## 冲突处理策略
### 保留当前分支版本
```bash
git checkout --ours <file>
git add <file>
```
### 保留传入分支版本
```bash
git checkout --theirs <file>
git add <file>
```
### 放弃合并
```bash
# 放弃 merge
git merge --abort
# 放弃 rebase
git rebase --abort
```
## 预防冲突的最佳实践
1. **及时同步代码** - 每天开始工作前拉取最新代码
2. **小步提交** - 频繁提交小的改动
3. **功能模块化** - 不同功能在不同文件中实现
4. **沟通协作** - 避免同时修改同一文件
## 常见冲突场景
### 场景1同一文件不同位置修改
这种情况 Git 通常能自动合并,无需人工干预。
### 场景2同一行不同修改
需要手动决定保留哪个版本或合并两者。
### 场景3文件重命名
Git 通常能智能识别,但如果一个分支重命名而另一个分支修改内容,可能需要手动处理。
### 场景4二进制文件冲突
对于图片、PDF 等二进制文件,需要决定保留哪个版本:
```bash
# 保留当前分支的版本
git checkout --ours image.png
# 或保留传入分支的版本
git checkout --theirs image.png
```
## 冲突解决工具
### 使用 merge 工具
```bash
# 配置合并工具
git config --global merge.tool vimdiff
git config --global mergetool.prompt false
# 使用合并工具
git mergetool
```
### 使用 diff 工具
```bash
# 查看详细差异
git diff --ours
git diff --theirs
git diff --base
```
## Rebase 冲突特殊处理
Rebase 时冲突会逐个提交出现,处理方式:
```bash
git rebase develop
# 冲突1 -> 解决 -> git add -> git rebase --continue
# 冲突2 -> 解决 -> git add -> git rebase --continue
# ...
# 直到完成
```
如果某一步想跳过:
```bash
git rebase --skip
```
如果整体想放弃:
```bash
git rebase --abort
```

View File

@@ -0,0 +1,276 @@
# .gitignore 规范
## 基本规则
```
# 空行:不匹配任何文件
# 注释:以 # 开头
# 目录:以 / 结尾
# 取反:以 ! 开头表示不忽略
# 根目录:以 / 开头表示项目根目录
*.log # 忽略所有 .log 文件
node_modules/ # 忽略 node_modules 目录
/temp/ # 忽略根目录下的 temp 目录
**/.env # 忽略所有目录下的 .env 文件
!.gitkeep # 不忽略 .gitkeep 文件
```
## 通用 .gitignore
```
# ============================================
# 依赖目录
# ============================================
node_modules/
vendor/
# ============================================
# 构建产物
# ============================================
dist/
build/
target/
# ============================================
# 编辑器和 IDE
# ============================================
.idea/
.vscode/
*.sw?
# ============================================
# 环境配置
# ============================================
.env
.env.local
.env.*.local
# ============================================
# 日志文件
# ============================================
logs/
*.log
npm-debug.log*
# ============================================
# 系统文件
# ============================================
.DS_Store
Thumbs.db
# ============================================
# 缓存文件
# ============================================
.cache/
.eslintcache
.stylelintcache
```
## 项目特定配置
### 前端/文档项目补充
```
# VitePress
docs/.vitepress/dist
docs/.vitepress/cache
# Node.js
package-lock.json
yarn.lock
pnpm-lock.yaml
```
### 后端项目补充
```
# Maven
target/
pom.xml.tag
*.jar
!**/src/main/**/target/
# 敏感配置
application-local.yml
application-dev.yml
```
### Python 项目补充
```
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
env/
ENV/
.pytest_cache/
# Jupyter Notebook
.ipynb_checkpoints
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype
.pytype/
```
### Go 项目补充
```
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool
*.out
# Dependency directories
vendor/
# Go workspace file
go.work
```
### Rust 项目补充
```
# Rust
/target/
**/*.rs.bk
*.pdb
Cargo.lock
```
## .gitignore 技巧
### 忽略文件但保留目录
```
logs/*
!logs/.gitkeep
```
### 检查忽略规则
```bash
git check-ignore -v filename
```
### 清理已提交的忽略文件
```bash
git rm --cached filename
git commit -m "chore: 移除不应提交的文件"
```
### 调试 .gitignore
```bash
# 查看文件是否被忽略以及被哪条规则匹配
git check-ignore -v path/to/file
# 查看所有被忽略的文件
git ls-files --others --ignored --exclude-standard
```
## 常见模式
### 忽略特定文件
```
# 忽略特定文件
config/local.json
secrets.yaml
```
### 忽略特定类型
```
# 忽略所有 .log 文件
*.log
# 忽略所有临时文件
*.tmp
*.temp
```
### 忽略目录
```
# 忽略所有 node_modules 目录
node_modules/
# 忽略根目录下的 build 目录
/build/
# 忽略任何位置的 build 目录
**/build/
```
### 取反规则
```
# 忽略所有 .a 文件
*.a
# 但不忽略 lib.a
!lib.a
# 忽略所有 TODO 文件
TODO*
# 但不忽略 TODO.md
!TODO.md
```
### 通配符
```
# * 匹配任意字符
*.log
# ** 匹配任意目录
**/temp/
# ? 匹配单个字符
file?.txt
# [] 匹配括号内任意字符
file[0-9].txt
```
## .gitignore 优先级
1. 命令行指定的文件(如 `git add -f`
2. `.git/info/exclude`(本地排除规则)
3. `.gitignore`(项目级别,提交到仓库)
4. `~/.gitignore_global`(全局级别)
### 本地排除规则
对于不想提交到仓库的本地忽略规则:
```bash
# 编辑本地排除文件
git config --global core.excludesfile ~/.gitignore_global
# 或者使用 .git/info/exclude仅当前仓库
echo "secrets.yaml" >> .git/info/exclude
```

View File

@@ -0,0 +1,121 @@
# 合并策略详解
## Merge vs Rebase
| 特性 | Merge | Rebase |
| :------- | :------------------------- | :----------------------- |
| 历史记录 | 保留完整历史,创建合并提交 | 线性历史,不创建合并提交 |
| 适用场景 | 公共分支、需要保留历史 | 私有分支、保持历史清晰 |
| 冲突处理 | 一次性处理所有冲突 | 逐个提交处理冲突 |
| 推荐用法 | 合并到主分支 | 同步上游代码 |
## 使用建议
### 功能分支同步 develop使用 rebase
```bash
git checkout feature/user-management
git rebase develop
```
### 功能分支合并到 develop使用 merge --no-ff
```bash
git checkout develop
git merge --no-ff feature/user-management
```
### develop 合并到 master使用 merge --no-ff
```bash
git checkout master
git merge --no-ff develop
```
### 禁止在公共分支上 rebase
```bash
# ❌ 危险操作
git checkout develop
git rebase feature/xxx # 会改写公共历史
```
## Fast-Forward vs No-Fast-Forward
### Fast-Forward 合并(不创建合并提交)
```bash
git merge feature/xxx
```
```
# A---B---C (master)
# \
# D---E (feature)
# 结果: A---B---C---D---E (master)
```
### No-Fast-Forward 合并(创建合并提交)
```bash
git merge --no-ff feature/xxx
```
```
# A---B---C---------M (master)
# \ /
# D---E (feature)
```
**项目约定**:合并功能分支时使用 `--no-ff`,保留分支历史信息。
## Squash 合并
将多个提交压缩成一个:
```bash
git checkout develop
git merge --squash feature/user-management
git commit -m "feat(user): 添加用户管理功能"
```
### 适用场景
- 功能分支有太多琐碎提交
- 想要保持主分支历史清晰
- 不需要保留开发过程中的细节
### Squash vs Merge --no-ff
| 策略 | 优点 | 缺点 | 适用场景 |
| :---------- | :----------------------- | :----------------------- | :--------------------- |
| merge --no-ff | 保留完整历史和开发过程 | 历史可能比较复杂 | 功能分支、重要功能 |
| squash | 历史清晰,一个提交一个功能 | 丢失开发过程信息 | 小功能、实验性功能 |
| rebase | 线性历史,易于理解 | 改写历史,可能引起问题 | 个人分支、同步上游 |
## Rebase 高级用法
### 交互式 Rebase
```bash
# 编辑最近5个提交
git rebase -i HEAD~5
```
在编辑器中可以使用以下命令:
- `pick` - 保留该提交
- `reword` - 修改提交消息
- `edit` - 修改提交内容
- `squash` - 合并到前一个提交
- `drop` - 删除该提交
### Rebase 时解决冲突
```bash
git rebase develop
# 出现冲突后,编辑文件解决冲突
git add <file>
git rebase --continue
# 如果想放弃 rebase
git rebase --abort
```

View File

@@ -0,0 +1,712 @@
---
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, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.
version: 0.1.0
---
# Hook Development for Claude Code Plugins
## Overview
Hooks are event-driven automation scripts that execute in response to Claude Code events. Use hooks to validate operations, enforce policies, add context, and integrate external tools into workflows.
**Key capabilities:**
- Validate tool calls before execution (PreToolUse)
- React to tool results (PostToolUse)
- Enforce completion standards (Stop, SubagentStop)
- Load project context (SessionStart)
- Automate workflows across the development lifecycle
## Hook Types
### Prompt-Based Hooks (Recommended)
Use LLM-driven decision making for context-aware validation:
```json
{
"type": "prompt",
"prompt": "Evaluate if this tool use is appropriate: $TOOL_INPUT",
"timeout": 30
}
```
**Supported events:** Stop, SubagentStop, UserPromptSubmit, PreToolUse
**Benefits:**
- Context-aware decisions based on natural language reasoning
- Flexible evaluation logic without bash scripting
- Better edge case handling
- Easier to maintain and extend
### Command Hooks
Execute bash commands for deterministic checks:
```json
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh",
"timeout": 60
}
```
**Use for:**
- Fast deterministic validations
- File system operations
- External tool integrations
- Performance-critical checks
## Hook Configuration Formats
### Plugin hooks.json Format
**For plugin hooks** in `hooks/hooks.json`, use wrapper format:
```json
{
"description": "Brief explanation of hooks (optional)",
"hooks": {
"PreToolUse": [...],
"Stop": [...],
"SessionStart": [...]
}
}
```
**Key points:**
- `description` field is optional
- `hooks` field is required wrapper containing actual hook events
- This is the **plugin-specific format**
**Example:**
```json
{
"description": "Validation hooks for code quality",
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/validate.sh"
}
]
}
]
}
}
```
### Settings Format (Direct)
**For user settings** in `.claude/settings.json`, use direct format:
```json
{
"PreToolUse": [...],
"Stop": [...],
"SessionStart": [...]
}
```
**Key points:**
- No wrapper - events directly at top level
- No description field
- This is the **settings format**
**Important:** The examples below show the hook event structure that goes inside either format. For plugin hooks.json, wrap these in `{"hooks": {...}}`.
## Hook Events
### PreToolUse
Execute before any tool runs. Use to approve, deny, or modify tool calls.
**Example (prompt-based):**
```json
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety. Check: system paths, credentials, path traversal, sensitive content. Return 'approve' or 'deny'."
}
]
}
]
}
```
**Output for PreToolUse:**
```json
{
"hookSpecificOutput": {
"permissionDecision": "allow|deny|ask",
"updatedInput": {"field": "modified_value"}
},
"systemMessage": "Explanation for Claude"
}
```
### PostToolUse
Execute after tool completes. Use to react to results, provide feedback, or log.
**Example:**
```json
{
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Analyze edit result for potential issues: syntax errors, security vulnerabilities, breaking changes. Provide feedback."
}
]
}
]
}
```
**Output behavior:**
- Exit 0: stdout shown in transcript
- Exit 2: stderr fed back to Claude
- systemMessage included in context
### Stop
Execute when main agent considers stopping. Use to validate completeness.
**Example:**
```json
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify task completion: tests run, build succeeded, questions answered. Return 'approve' to stop or 'block' with reason to continue."
}
]
}
]
}
```
**Decision output:**
```json
{
"decision": "approve|block",
"reason": "Explanation",
"systemMessage": "Additional context"
}
```
### SubagentStop
Execute when subagent considers stopping. Use to ensure subagent completed its task.
Similar to Stop hook, but for subagents.
### UserPromptSubmit
Execute when user submits a prompt. Use to add context, validate, or block prompts.
**Example:**
```json
{
"UserPromptSubmit": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Check if prompt requires security guidance. If discussing auth, permissions, or API security, return relevant warnings."
}
]
}
]
}
```
### SessionStart
Execute when Claude Code session begins. Use to load context and set environment.
**Example:**
```json
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
}
]
}
]
}
```
**Special capability:** Persist environment variables using `$CLAUDE_ENV_FILE`:
```bash
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
```
See `examples/load-context.sh` for complete example.
### SessionEnd
Execute when session ends. Use for cleanup, logging, and state preservation.
### PreCompact
Execute before context compaction. Use to add critical information to preserve.
### Notification
Execute when Claude sends notifications. Use to react to user notifications.
## Hook Output Format
### Standard Output (All Hooks)
```json
{
"continue": true,
"suppressOutput": false,
"systemMessage": "Message for Claude"
}
```
- `continue`: If false, halt processing (default true)
- `suppressOutput`: Hide output from transcript (default false)
- `systemMessage`: Message shown to Claude
### Exit Codes
- `0` - Success (stdout shown in transcript)
- `2` - Blocking error (stderr fed back to Claude)
- Other - Non-blocking error
## Hook Input Format
All hooks receive JSON via stdin with common fields:
```json
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.txt",
"cwd": "/current/working/dir",
"permission_mode": "ask|allow",
"hook_event_name": "PreToolUse"
}
```
**Event-specific fields:**
- **PreToolUse/PostToolUse:** `tool_name`, `tool_input`, `tool_result`
- **UserPromptSubmit:** `user_prompt`
- **Stop/SubagentStop:** `reason`
Access fields in prompts using `$TOOL_INPUT`, `$TOOL_RESULT`, `$USER_PROMPT`, etc.
## Environment Variables
Available in all command hooks:
- `$CLAUDE_PROJECT_DIR` - Project root path
- `$CLAUDE_PLUGIN_ROOT` - Plugin directory (use for portable paths)
- `$CLAUDE_ENV_FILE` - SessionStart only: persist env vars here
- `$CLAUDE_CODE_REMOTE` - Set if running in remote context
**Always use ${CLAUDE_PLUGIN_ROOT} in hook commands for portability:**
```json
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
}
```
## Plugin Hook Configuration
In plugins, define hooks in `hooks/hooks.json`:
```json
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety"
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify task completion"
}
]
}
],
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh",
"timeout": 10
}
]
}
]
}
```
Plugin hooks merge with user's hooks and run in parallel.
## Matchers
### Tool Name Matching
**Exact match:**
```json
"matcher": "Write"
```
**Multiple tools:**
```json
"matcher": "Read|Write|Edit"
```
**Wildcard (all tools):**
```json
"matcher": "*"
```
**Regex patterns:**
```json
"matcher": "mcp__.*__delete.*" // All MCP delete tools
```
**Note:** Matchers are case-sensitive.
### Common Patterns
```json
// All MCP tools
"matcher": "mcp__.*"
// Specific plugin's MCP tools
"matcher": "mcp__plugin_asana_.*"
// All file operations
"matcher": "Read|Write|Edit"
// Bash commands only
"matcher": "Bash"
```
## Security Best Practices
### Input Validation
Always validate inputs in command hooks:
```bash
#!/bin/bash
set -euo pipefail
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
# Validate tool name format
if [[ ! "$tool_name" =~ ^[a-zA-Z0-9_]+$ ]]; then
echo '{"decision": "deny", "reason": "Invalid tool name"}' >&2
exit 2
fi
```
### Path Safety
Check for path traversal and sensitive files:
```bash
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
# Deny path traversal
if [[ "$file_path" == *".."* ]]; then
echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
exit 2
fi
# Deny sensitive files
if [[ "$file_path" == *".env"* ]]; then
echo '{"decision": "deny", "reason": "Sensitive file"}' >&2
exit 2
fi
```
See `examples/validate-write.sh` and `examples/validate-bash.sh` for complete examples.
### Quote All Variables
```bash
# GOOD: Quoted
echo "$file_path"
cd "$CLAUDE_PROJECT_DIR"
# BAD: Unquoted (injection risk)
echo $file_path
cd $CLAUDE_PROJECT_DIR
```
### Set Appropriate Timeouts
```json
{
"type": "command",
"command": "bash script.sh",
"timeout": 10
}
```
**Defaults:** Command hooks (60s), Prompt hooks (30s)
## Performance Considerations
### Parallel Execution
All matching hooks run **in parallel**:
```json
{
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{"type": "command", "command": "check1.sh"}, // Parallel
{"type": "command", "command": "check2.sh"}, // Parallel
{"type": "prompt", "prompt": "Validate..."} // Parallel
]
}
]
}
```
**Design implications:**
- Hooks don't see each other's output
- Non-deterministic ordering
- Design for independence
### Optimization
1. Use command hooks for quick deterministic checks
2. Use prompt hooks for complex reasoning
3. Cache validation results in temp files
4. Minimize I/O in hot paths
## Temporarily Active Hooks
Create hooks that activate conditionally by checking for a flag file or configuration:
**Pattern: Flag file activation**
```bash
#!/bin/bash
# Only active when flag file exists
FLAG_FILE="$CLAUDE_PROJECT_DIR/.enable-strict-validation"
if [ ! -f "$FLAG_FILE" ]; then
# Flag not present, skip validation
exit 0
fi
# Flag present, run validation
input=$(cat)
# ... validation logic ...
```
**Pattern: Configuration-based activation**
```bash
#!/bin/bash
# Check configuration for activation
CONFIG_FILE="$CLAUDE_PROJECT_DIR/.claude/plugin-config.json"
if [ -f "$CONFIG_FILE" ]; then
enabled=$(jq -r '.strictMode // false' "$CONFIG_FILE")
if [ "$enabled" != "true" ]; then
exit 0 # Not enabled, skip
fi
fi
# Enabled, run hook logic
input=$(cat)
# ... hook logic ...
```
**Use cases:**
- Enable strict validation only when needed
- Temporary debugging hooks
- Project-specific hook behavior
- Feature flags for hooks
**Best practice:** Document activation mechanism in plugin README so users know how to enable/disable temporary hooks.
## Hook Lifecycle and Limitations
### Hooks Load at Session Start
**Important:** Hooks are loaded when Claude Code session starts. Changes to hook configuration require restarting Claude Code.
**Cannot hot-swap hooks:**
- Editing `hooks/hooks.json` won't affect current session
- Adding new hook scripts won't be recognized
- Changing hook commands/prompts won't update
- Must restart Claude Code: exit and run `claude` again
**To test hook changes:**
1. Edit hook configuration or scripts
2. Exit Claude Code session
3. Restart: `claude` or `cc`
4. New hook configuration loads
5. Test hooks with `claude --debug`
### Hook Validation at Startup
Hooks are validated when Claude Code starts:
- Invalid JSON in hooks.json causes loading failure
- Missing scripts cause warnings
- Syntax errors reported in debug mode
Use `/hooks` command to review loaded hooks in current session.
## Debugging Hooks
### Enable Debug Mode
```bash
claude --debug
```
Look for hook registration, execution logs, input/output JSON, and timing information.
### Test Hook Scripts
Test command hooks directly:
```bash
echo '{"tool_name": "Write", "tool_input": {"file_path": "/test"}}' | \
bash ${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh
echo "Exit code: $?"
```
### Validate JSON Output
Ensure hooks output valid JSON:
```bash
output=$(./your-hook.sh < test-input.json)
echo "$output" | jq .
```
## Quick Reference
### Hook Events Summary
| Event | When | Use For |
|-------|------|---------|
| PreToolUse | Before tool | Validation, modification |
| PostToolUse | After tool | Feedback, logging |
| UserPromptSubmit | User input | Context, validation |
| Stop | Agent stopping | Completeness check |
| SubagentStop | Subagent done | Task validation |
| SessionStart | Session begins | Context loading |
| SessionEnd | Session ends | Cleanup, logging |
| PreCompact | Before compact | Preserve context |
| Notification | User notified | Logging, reactions |
### Best Practices
**DO:**
- ✅ Use prompt-based hooks for complex logic
- ✅ Use ${CLAUDE_PLUGIN_ROOT} for portability
- ✅ Validate all inputs in command hooks
- ✅ Quote all bash variables
- ✅ Set appropriate timeouts
- ✅ Return structured JSON output
- ✅ Test hooks thoroughly
**DON'T:**
- ❌ Use hardcoded paths
- ❌ Trust user input without validation
- ❌ Create long-running hooks
- ❌ Rely on hook execution order
- ❌ Modify global state unpredictably
- ❌ Log sensitive information
## Additional Resources
### Reference Files
For detailed patterns and advanced techniques, consult:
- **`references/patterns.md`** - Common hook patterns (8+ proven patterns)
- **`references/migration.md`** - Migrating from basic to advanced hooks
- **`references/advanced.md`** - Advanced use cases and techniques
### Example Hook Scripts
Working examples in `examples/`:
- **`validate-write.sh`** - File write validation example
- **`validate-bash.sh`** - Bash command validation example
- **`load-context.sh`** - SessionStart context loading example
### Utility Scripts
Development tools in `scripts/`:
- **`validate-hook-schema.sh`** - Validate hooks.json structure and syntax
- **`test-hook.sh`** - Test hooks with sample input before deployment
- **`hook-linter.sh`** - Check hook scripts for common issues and best practices
### External Resources
- **Official Docs**: https://docs.claude.com/en/docs/claude-code/hooks
- **Examples**: See security-guidance plugin in marketplace
- **Testing**: Use `claude --debug` for detailed logs
- **Validation**: Use `jq` to validate hook JSON output
## Implementation Workflow
To implement hooks in a plugin:
1. Identify events to hook into (PreToolUse, Stop, SessionStart, etc.)
2. Decide between prompt-based (flexible) or command (deterministic) hooks
3. Write hook configuration in `hooks/hooks.json`
4. For command hooks, create hook scripts
5. Use ${CLAUDE_PLUGIN_ROOT} for all file references
6. Validate configuration with `scripts/validate-hook-schema.sh hooks/hooks.json`
7. Test hooks with `scripts/test-hook.sh` before deployment
8. Test in Claude Code with `claude --debug`
9. Document hooks in plugin README
Focus on prompt-based hooks for most use cases. Reserve command hooks for performance-critical or deterministic checks.

View File

@@ -0,0 +1,55 @@
#!/bin/bash
# Example SessionStart hook for loading project context
# This script detects project type and sets environment variables
set -euo pipefail
# Navigate to project directory
cd "$CLAUDE_PROJECT_DIR" || exit 1
echo "Loading project context..."
# Detect project type and set environment
if [ -f "package.json" ]; then
echo "📦 Node.js project detected"
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
# Check if TypeScript
if [ -f "tsconfig.json" ]; then
echo "export USES_TYPESCRIPT=true" >> "$CLAUDE_ENV_FILE"
fi
elif [ -f "Cargo.toml" ]; then
echo "🦀 Rust project detected"
echo "export PROJECT_TYPE=rust" >> "$CLAUDE_ENV_FILE"
elif [ -f "go.mod" ]; then
echo "🐹 Go project detected"
echo "export PROJECT_TYPE=go" >> "$CLAUDE_ENV_FILE"
elif [ -f "pyproject.toml" ] || [ -f "setup.py" ]; then
echo "🐍 Python project detected"
echo "export PROJECT_TYPE=python" >> "$CLAUDE_ENV_FILE"
elif [ -f "pom.xml" ]; then
echo "☕ Java (Maven) project detected"
echo "export PROJECT_TYPE=java" >> "$CLAUDE_ENV_FILE"
echo "export BUILD_SYSTEM=maven" >> "$CLAUDE_ENV_FILE"
elif [ -f "build.gradle" ] || [ -f "build.gradle.kts" ]; then
echo "☕ Java/Kotlin (Gradle) project detected"
echo "export PROJECT_TYPE=java" >> "$CLAUDE_ENV_FILE"
echo "export BUILD_SYSTEM=gradle" >> "$CLAUDE_ENV_FILE"
else
echo "❓ Unknown project type"
echo "export PROJECT_TYPE=unknown" >> "$CLAUDE_ENV_FILE"
fi
# Check for CI configuration
if [ -f ".github/workflows" ] || [ -f ".gitlab-ci.yml" ] || [ -f ".circleci/config.yml" ]; then
echo "export HAS_CI=true" >> "$CLAUDE_ENV_FILE"
fi
echo "Project context loaded successfully"
exit 0

View File

@@ -0,0 +1,43 @@
#!/bin/bash
# Example PreToolUse hook for validating Bash commands
# This script demonstrates bash command validation patterns
set -euo pipefail
# Read input from stdin
input=$(cat)
# Extract command
command=$(echo "$input" | jq -r '.tool_input.command // empty')
# Validate command exists
if [ -z "$command" ]; then
echo '{"continue": true}' # No command to validate
exit 0
fi
# Check for obviously safe commands (quick approval)
if [[ "$command" =~ ^(ls|pwd|echo|date|whoami)(\s|$) ]]; then
exit 0
fi
# Check for destructive operations
if [[ "$command" == *"rm -rf"* ]] || [[ "$command" == *"rm -fr"* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Dangerous command detected: rm -rf"}' >&2
exit 2
fi
# Check for other dangerous commands
if [[ "$command" == *"dd if="* ]] || [[ "$command" == *"mkfs"* ]] || [[ "$command" == *"> /dev/"* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Dangerous system operation detected"}' >&2
exit 2
fi
# Check for privilege escalation
if [[ "$command" == sudo* ]] || [[ "$command" == su* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "ask"}, "systemMessage": "Command requires elevated privileges"}' >&2
exit 2
fi
# Approve the operation
exit 0

View File

@@ -0,0 +1,38 @@
#!/bin/bash
# Example PreToolUse hook for validating Write/Edit operations
# This script demonstrates file write validation patterns
set -euo pipefail
# Read input from stdin
input=$(cat)
# Extract file path and content
file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty')
# Validate path exists
if [ -z "$file_path" ]; then
echo '{"continue": true}' # No path to validate
exit 0
fi
# Check for path traversal
if [[ "$file_path" == *".."* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Path traversal detected in: '"$file_path"'"}' >&2
exit 2
fi
# Check for system directories
if [[ "$file_path" == /etc/* ]] || [[ "$file_path" == /sys/* ]] || [[ "$file_path" == /usr/* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "deny"}, "systemMessage": "Cannot write to system directory: '"$file_path"'"}' >&2
exit 2
fi
# Check for sensitive files
if [[ "$file_path" == *.env ]] || [[ "$file_path" == *secret* ]] || [[ "$file_path" == *credentials* ]]; then
echo '{"hookSpecificOutput": {"permissionDecision": "ask"}, "systemMessage": "Writing to potentially sensitive file: '"$file_path"'"}' >&2
exit 2
fi
# Approve the operation
exit 0

View File

@@ -0,0 +1,479 @@
# Advanced Hook Use Cases
This reference covers advanced hook patterns and techniques for sophisticated automation workflows.
## Multi-Stage Validation
Combine command and prompt hooks for layered validation:
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/quick-check.sh",
"timeout": 5
},
{
"type": "prompt",
"prompt": "Deep analysis of bash command: $TOOL_INPUT",
"timeout": 15
}
]
}
]
}
```
**Use case:** Fast deterministic checks followed by intelligent analysis
**Example quick-check.sh:**
```bash
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')
# Immediate approval for safe commands
if [[ "$command" =~ ^(ls|pwd|echo|date|whoami)$ ]]; then
exit 0
fi
# Let prompt hook handle complex cases
exit 0
```
The command hook quickly approves obviously safe commands, while the prompt hook analyzes everything else.
## Conditional Hook Execution
Execute hooks based on environment or context:
```bash
#!/bin/bash
# Only run in CI environment
if [ -z "$CI" ]; then
echo '{"continue": true}' # Skip in non-CI
exit 0
fi
# Run validation logic in CI
input=$(cat)
# ... validation code ...
```
**Use cases:**
- Different behavior in CI vs local development
- Project-specific validation
- User-specific rules
**Example: Skip certain checks for trusted users:**
```bash
#!/bin/bash
# Skip detailed checks for admin users
if [ "$USER" = "admin" ]; then
exit 0
fi
# Full validation for other users
input=$(cat)
# ... validation code ...
```
## Hook Chaining via State
Share state between hooks using temporary files:
```bash
# Hook 1: Analyze and save state
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')
# Analyze command
risk_level=$(calculate_risk "$command")
echo "$risk_level" > /tmp/hook-state-$$
exit 0
```
```bash
# Hook 2: Use saved state
#!/bin/bash
risk_level=$(cat /tmp/hook-state-$$ 2>/dev/null || echo "unknown")
if [ "$risk_level" = "high" ]; then
echo "High risk operation detected" >&2
exit 2
fi
```
**Important:** This only works for sequential hook events (e.g., PreToolUse then PostToolUse), not parallel hooks.
## Dynamic Hook Configuration
Modify hook behavior based on project configuration:
```bash
#!/bin/bash
cd "$CLAUDE_PROJECT_DIR" || exit 1
# Read project-specific config
if [ -f ".claude-hooks-config.json" ]; then
strict_mode=$(jq -r '.strict_mode' .claude-hooks-config.json)
if [ "$strict_mode" = "true" ]; then
# Apply strict validation
# ...
else
# Apply lenient validation
# ...
fi
fi
```
**Example .claude-hooks-config.json:**
```json
{
"strict_mode": true,
"allowed_commands": ["ls", "pwd", "grep"],
"forbidden_paths": ["/etc", "/sys"]
}
```
## Context-Aware Prompt Hooks
Use transcript and session context for intelligent decisions:
```json
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Review the full transcript at $TRANSCRIPT_PATH. Check: 1) Were tests run after code changes? 2) Did the build succeed? 3) Were all user questions answered? 4) Is there any unfinished work? Return 'approve' only if everything is complete."
}
]
}
]
}
```
The LLM can read the transcript file and make context-aware decisions.
## Performance Optimization
### Caching Validation Results
```bash
#!/bin/bash
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
cache_key=$(echo -n "$file_path" | md5sum | cut -d' ' -f1)
cache_file="/tmp/hook-cache-$cache_key"
# Check cache
if [ -f "$cache_file" ]; then
cache_age=$(($(date +%s) - $(stat -f%m "$cache_file" 2>/dev/null || stat -c%Y "$cache_file")))
if [ "$cache_age" -lt 300 ]; then # 5 minute cache
cat "$cache_file"
exit 0
fi
fi
# Perform validation
result='{"decision": "approve"}'
# Cache result
echo "$result" > "$cache_file"
echo "$result"
```
### Parallel Execution Optimization
Since hooks run in parallel, design them to be independent:
```json
{
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "bash check-size.sh", // Independent
"timeout": 2
},
{
"type": "command",
"command": "bash check-path.sh", // Independent
"timeout": 2
},
{
"type": "prompt",
"prompt": "Check content safety", // Independent
"timeout": 10
}
]
}
]
}
```
All three hooks run simultaneously, reducing total latency.
## Cross-Event Workflows
Coordinate hooks across different events:
**SessionStart - Set up tracking:**
```bash
#!/bin/bash
# Initialize session tracking
echo "0" > /tmp/test-count-$$
echo "0" > /tmp/build-count-$$
```
**PostToolUse - Track events:**
```bash
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
if [ "$tool_name" = "Bash" ]; then
command=$(echo "$input" | jq -r '.tool_result')
if [[ "$command" == *"test"* ]]; then
count=$(cat /tmp/test-count-$$ 2>/dev/null || echo "0")
echo $((count + 1)) > /tmp/test-count-$$
fi
fi
```
**Stop - Verify based on tracking:**
```bash
#!/bin/bash
test_count=$(cat /tmp/test-count-$$ 2>/dev/null || echo "0")
if [ "$test_count" -eq 0 ]; then
echo '{"decision": "block", "reason": "No tests were run"}' >&2
exit 2
fi
```
## Integration with External Systems
### Slack Notifications
```bash
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
decision="blocked"
# Send notification to Slack
curl -X POST "$SLACK_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\": \"Hook ${decision} ${tool_name} operation\"}" \
2>/dev/null
echo '{"decision": "deny"}' >&2
exit 2
```
### Database Logging
```bash
#!/bin/bash
input=$(cat)
# Log to database
psql "$DATABASE_URL" -c "INSERT INTO hook_logs (event, data) VALUES ('PreToolUse', '$input')" \
2>/dev/null
exit 0
```
### Metrics Collection
```bash
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
# Send metrics to monitoring system
echo "hook.pretooluse.${tool_name}:1|c" | nc -u -w1 statsd.local 8125
exit 0
```
## Security Patterns
### Rate Limiting
```bash
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')
# Track command frequency
rate_file="/tmp/hook-rate-$$"
current_minute=$(date +%Y%m%d%H%M)
if [ -f "$rate_file" ]; then
last_minute=$(head -1 "$rate_file")
count=$(tail -1 "$rate_file")
if [ "$current_minute" = "$last_minute" ]; then
if [ "$count" -gt 10 ]; then
echo '{"decision": "deny", "reason": "Rate limit exceeded"}' >&2
exit 2
fi
count=$((count + 1))
else
count=1
fi
else
count=1
fi
echo "$current_minute" > "$rate_file"
echo "$count" >> "$rate_file"
exit 0
```
### Audit Logging
```bash
#!/bin/bash
input=$(cat)
tool_name=$(echo "$input" | jq -r '.tool_name')
timestamp=$(date -Iseconds)
# Append to audit log
echo "$timestamp | $USER | $tool_name | $input" >> ~/.claude/audit.log
exit 0
```
### Secret Detection
```bash
#!/bin/bash
input=$(cat)
content=$(echo "$input" | jq -r '.tool_input.content')
# Check for common secret patterns
if echo "$content" | grep -qE "(api[_-]?key|password|secret|token).{0,20}['\"]?[A-Za-z0-9]{20,}"; then
echo '{"decision": "deny", "reason": "Potential secret detected in content"}' >&2
exit 2
fi
exit 0
```
## Testing Advanced Hooks
### Unit Testing Hook Scripts
```bash
# test-hook.sh
#!/bin/bash
# Test 1: Approve safe command
result=$(echo '{"tool_input": {"command": "ls"}}' | bash validate-bash.sh)
if [ $? -eq 0 ]; then
echo "✓ Test 1 passed"
else
echo "✗ Test 1 failed"
fi
# Test 2: Block dangerous command
result=$(echo '{"tool_input": {"command": "rm -rf /"}}' | bash validate-bash.sh)
if [ $? -eq 2 ]; then
echo "✓ Test 2 passed"
else
echo "✗ Test 2 failed"
fi
```
### Integration Testing
Create test scenarios that exercise the full hook workflow:
```bash
# integration-test.sh
#!/bin/bash
# Set up test environment
export CLAUDE_PROJECT_DIR="/tmp/test-project"
export CLAUDE_PLUGIN_ROOT="$(pwd)"
mkdir -p "$CLAUDE_PROJECT_DIR"
# Test SessionStart hook
echo '{}' | bash hooks/session-start.sh
if [ -f "/tmp/session-initialized" ]; then
echo "✓ SessionStart hook works"
else
echo "✗ SessionStart hook failed"
fi
# Clean up
rm -rf "$CLAUDE_PROJECT_DIR"
```
## Best Practices for Advanced Hooks
1. **Keep hooks independent**: Don't rely on execution order
2. **Use timeouts**: Set appropriate limits for each hook type
3. **Handle errors gracefully**: Provide clear error messages
4. **Document complexity**: Explain advanced patterns in README
5. **Test thoroughly**: Cover edge cases and failure modes
6. **Monitor performance**: Track hook execution time
7. **Version configuration**: Use version control for hook configs
8. **Provide escape hatches**: Allow users to bypass hooks when needed
## Common Pitfalls
### ❌ Assuming Hook Order
```bash
# BAD: Assumes hooks run in specific order
# Hook 1 saves state, Hook 2 reads it
# This can fail because hooks run in parallel!
```
### ❌ Long-Running Hooks
```bash
# BAD: Hook takes 2 minutes to run
sleep 120
# This will timeout and block the workflow
```
### ❌ Uncaught Exceptions
```bash
# BAD: Script crashes on unexpected input
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
cat "$file_path" # Fails if file doesn't exist
```
### ✅ Proper Error Handling
```bash
# GOOD: Handles errors gracefully
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
if [ ! -f "$file_path" ]; then
echo '{"continue": true, "systemMessage": "File not found, skipping check"}' >&2
exit 0
fi
```
## 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.

View File

@@ -0,0 +1,369 @@
# Migrating from Basic to Advanced Hooks
This guide shows how to migrate from basic command hooks to advanced prompt-based hooks for better maintainability and flexibility.
## Why Migrate?
Prompt-based hooks offer several advantages:
- **Natural language reasoning**: LLM understands context and intent
- **Better edge case handling**: Adapts to unexpected scenarios
- **No bash scripting required**: Simpler to write and maintain
- **More flexible validation**: Can handle complex logic without coding
## Migration Example: Bash Command Validation
### Before (Basic Command Hook)
**Configuration:**
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash validate-bash.sh"
}
]
}
]
}
```
**Script (validate-bash.sh):**
```bash
#!/bin/bash
input=$(cat)
command=$(echo "$input" | jq -r '.tool_input.command')
# Hard-coded validation logic
if [[ "$command" == *"rm -rf"* ]]; then
echo "Dangerous command detected" >&2
exit 2
fi
```
**Problems:**
- Only checks for exact "rm -rf" pattern
- Doesn't catch variations like `rm -fr` or `rm -r -f`
- Misses other dangerous commands (`dd`, `mkfs`, etc.)
- No context awareness
- Requires bash scripting knowledge
### After (Advanced Prompt Hook)
**Configuration:**
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Command: $TOOL_INPUT.command. Analyze for: 1) Destructive operations (rm -rf, dd, mkfs, etc) 2) Privilege escalation (sudo) 3) Network operations without user consent. Return 'approve' or 'deny' with explanation.",
"timeout": 15
}
]
}
]
}
```
**Benefits:**
- Catches all variations and patterns
- Understands intent, not just literal strings
- No script file needed
- Easy to extend with new criteria
- Context-aware decisions
- Natural language explanation in denial
## Migration Example: File Write Validation
### Before (Basic Command Hook)
**Configuration:**
```json
{
"PreToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "bash validate-write.sh"
}
]
}
]
}
```
**Script (validate-write.sh):**
```bash
#!/bin/bash
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
# Check for path traversal
if [[ "$file_path" == *".."* ]]; then
echo '{"decision": "deny", "reason": "Path traversal detected"}' >&2
exit 2
fi
# Check for system paths
if [[ "$file_path" == "/etc/"* ]] || [[ "$file_path" == "/sys/"* ]]; then
echo '{"decision": "deny", "reason": "System file"}' >&2
exit 2
fi
```
**Problems:**
- Hard-coded path patterns
- Doesn't understand symlinks
- Missing edge cases (e.g., `/etc` vs `/etc/`)
- No consideration of file content
### After (Advanced Prompt Hook)
**Configuration:**
```json
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "File path: $TOOL_INPUT.file_path. Content preview: $TOOL_INPUT.content (first 200 chars). Verify: 1) Not system directories (/etc, /sys, /usr) 2) Not credentials (.env, tokens, secrets) 3) No path traversal 4) Content doesn't expose secrets. Return 'approve' or 'deny'."
}
]
}
]
}
```
**Benefits:**
- Context-aware (considers content too)
- Handles symlinks and edge cases
- Natural understanding of "system directories"
- Can detect secrets in content
- Easy to extend criteria
## When to Keep Command Hooks
Command hooks still have their place:
### 1. Deterministic Performance Checks
```bash
#!/bin/bash
# Check file size quickly
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
size=$(stat -f%z "$file_path" 2>/dev/null || stat -c%s "$file_path" 2>/dev/null)
if [ "$size" -gt 10000000 ]; then
echo '{"decision": "deny", "reason": "File too large"}' >&2
exit 2
fi
```
**Use command hooks when:** Validation is purely mathematical or deterministic.
### 2. External Tool Integration
```bash
#!/bin/bash
# Run security scanner
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
scan_result=$(security-scanner "$file_path")
if [ "$?" -ne 0 ]; then
echo "Security scan failed: $scan_result" >&2
exit 2
fi
```
**Use command hooks when:** Integrating with external tools that provide yes/no answers.
### 3. Very Fast Checks (< 50ms)
```bash
#!/bin/bash
# Quick regex check
command=$(echo "$input" | jq -r '.tool_input.command')
if [[ "$command" =~ ^(ls|pwd|echo)$ ]]; then
exit 0 # Safe commands
fi
```
**Use command hooks when:** Performance is critical and logic is simple.
## Hybrid Approach
Combine both for multi-stage validation:
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/quick-check.sh",
"timeout": 5
},
{
"type": "prompt",
"prompt": "Deep analysis of bash command: $TOOL_INPUT",
"timeout": 15
}
]
}
]
}
```
The command hook does fast deterministic checks, while the prompt hook handles complex reasoning.
## Migration Checklist
When migrating hooks:
- [ ] Identify the validation logic in the command hook
- [ ] Convert hard-coded patterns to natural language criteria
- [ ] Test with edge cases the old hook missed
- [ ] Verify LLM understands the intent
- [ ] Set appropriate timeout (usually 15-30s for prompt hooks)
- [ ] Document the new hook in README
- [ ] Remove or archive old script files
## Migration Tips
1. **Start with one hook**: Don't migrate everything at once
2. **Test thoroughly**: Verify prompt hook catches what command hook caught
3. **Look for improvements**: Use migration as opportunity to enhance validation
4. **Keep scripts for reference**: Archive old scripts in case you need to reference the logic
5. **Document reasoning**: Explain why prompt hook is better in README
## Complete Migration Example
### Original Plugin Structure
```
my-plugin/
├── .claude-plugin/plugin.json
├── hooks/hooks.json
└── scripts/
├── validate-bash.sh
├── validate-write.sh
└── check-tests.sh
```
### After Migration
```
my-plugin/
├── .claude-plugin/plugin.json
├── hooks/hooks.json # Now uses prompt hooks
└── scripts/ # Archive or delete
└── archive/
├── validate-bash.sh
├── validate-write.sh
└── check-tests.sh
```
### Updated hooks.json
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Validate bash command safety: destructive ops, privilege escalation, network access"
}
]
},
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety: system paths, credentials, path traversal, content secrets"
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify tests were run if code was modified"
}
]
}
]
}
```
**Result:** Simpler, more maintainable, more powerful.
## Common Migration Patterns
### Pattern: String Contains → Natural Language
**Before:**
```bash
if [[ "$command" == *"sudo"* ]]; then
echo "Privilege escalation" >&2
exit 2
fi
```
**After:**
```
"Check for privilege escalation (sudo, su, etc)"
```
### Pattern: Regex → Intent
**Before:**
```bash
if [[ "$file" =~ \.(env|secret|key|token)$ ]]; then
echo "Credential file" >&2
exit 2
fi
```
**After:**
```
"Verify not writing to credential files (.env, secrets, keys, tokens)"
```
### Pattern: Multiple Conditions → Criteria List
**Before:**
```bash
if [ condition1 ] || [ condition2 ] || [ condition3 ]; then
echo "Invalid" >&2
exit 2
fi
```
**After:**
```
"Check: 1) condition1 2) condition2 3) condition3. Deny if any fail."
```
## Conclusion
Migrating to prompt-based hooks makes plugins more maintainable, flexible, and powerful. Reserve command hooks for deterministic checks and external tool integration.

View File

@@ -0,0 +1,346 @@
# Common Hook Patterns
This reference provides common, proven patterns for implementing Claude Code hooks. Use these patterns as starting points for typical hook use cases.
## Pattern 1: Security Validation
Block dangerous file writes using prompt-based hooks:
```json
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "File path: $TOOL_INPUT.file_path. Verify: 1) Not in /etc or system directories 2) Not .env or credentials 3) Path doesn't contain '..' traversal. Return 'approve' or 'deny'."
}
]
}
]
}
```
**Use for:** Preventing writes to sensitive files or system directories.
## Pattern 2: Test Enforcement
Ensure tests run before stopping:
```json
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Review transcript. If code was modified (Write/Edit tools used), verify tests were executed. If no tests were run, block with reason 'Tests must be run after code changes'."
}
]
}
]
}
```
**Use for:** Enforcing quality standards and preventing incomplete work.
## Pattern 3: Context Loading
Load project-specific context at session start:
```json
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
}
]
}
]
}
```
**Example script (load-context.sh):**
```bash
#!/bin/bash
cd "$CLAUDE_PROJECT_DIR" || exit 1
# Detect project type
if [ -f "package.json" ]; then
echo "📦 Node.js project detected"
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
elif [ -f "Cargo.toml" ]; then
echo "🦀 Rust project detected"
echo "export PROJECT_TYPE=rust" >> "$CLAUDE_ENV_FILE"
fi
```
**Use for:** Automatically detecting and configuring project-specific settings.
## Pattern 4: Notification Logging
Log all notifications for audit or analysis:
```json
{
"Notification": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/log-notification.sh"
}
]
}
]
}
```
**Use for:** Tracking user notifications or integration with external logging systems.
## Pattern 5: MCP Tool Monitoring
Monitor and validate MCP tool usage:
```json
{
"PreToolUse": [
{
"matcher": "mcp__.*__delete.*",
"hooks": [
{
"type": "prompt",
"prompt": "Deletion operation detected. Verify: Is this deletion intentional? Can it be undone? Are there backups? Return 'approve' only if safe."
}
]
}
]
}
```
**Use for:** Protecting against destructive MCP operations.
## Pattern 6: Build Verification
Ensure project builds after code changes:
```json
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Check if code was modified. If Write/Edit tools were used, verify the project was built (npm run build, cargo build, etc). If not built, block and request build."
}
]
}
]
}
```
**Use for:** Catching build errors before committing or stopping work.
## Pattern 7: Permission Confirmation
Ask user before dangerous operations:
```json
{
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Command: $TOOL_INPUT.command. If command contains 'rm', 'delete', 'drop', or other destructive operations, return 'ask' to confirm with user. Otherwise 'approve'."
}
]
}
]
}
```
**Use for:** User confirmation on potentially destructive commands.
## Pattern 8: Code Quality Checks
Run linters or formatters on file edits:
```json
{
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/check-quality.sh"
}
]
}
]
}
```
**Example script (check-quality.sh):**
```bash
#!/bin/bash
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
# Run linter if applicable
if [[ "$file_path" == *.js ]] || [[ "$file_path" == *.ts ]]; then
npx eslint "$file_path" 2>&1 || true
fi
```
**Use for:** Automatic code quality enforcement.
## Pattern Combinations
Combine multiple patterns for comprehensive protection:
```json
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "Validate file write safety"
}
]
},
{
"matcher": "Bash",
"hooks": [
{
"type": "prompt",
"prompt": "Validate bash command safety"
}
]
}
],
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Verify tests run and build succeeded"
}
]
}
],
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
}
]
}
]
}
```
This provides multi-layered protection and automation.
## Pattern 9: Temporarily Active Hooks
Create hooks that only run when explicitly enabled via flag files:
```bash
#!/bin/bash
# Hook only active when flag file exists
FLAG_FILE="$CLAUDE_PROJECT_DIR/.enable-security-scan"
if [ ! -f "$FLAG_FILE" ]; then
# Quick exit when disabled
exit 0
fi
# Flag present, run validation
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path')
# Run security scan
security-scanner "$file_path"
```
**Activation:**
```bash
# Enable the hook
touch .enable-security-scan
# Disable the hook
rm .enable-security-scan
```
**Use for:**
- Temporary debugging hooks
- Feature flags for development
- Project-specific validation that's opt-in
- Performance-intensive checks only when needed
**Note:** Must restart Claude Code after creating/removing flag files for hooks to recognize changes.
## Pattern 10: Configuration-Driven Hooks
Use JSON configuration to control hook behavior:
```bash
#!/bin/bash
CONFIG_FILE="$CLAUDE_PROJECT_DIR/.claude/my-plugin.local.json"
# Read configuration
if [ -f "$CONFIG_FILE" ]; then
strict_mode=$(jq -r '.strictMode // false' "$CONFIG_FILE")
max_file_size=$(jq -r '.maxFileSize // 1000000' "$CONFIG_FILE")
else
# Defaults
strict_mode=false
max_file_size=1000000
fi
# Skip if not in strict mode
if [ "$strict_mode" != "true" ]; then
exit 0
fi
# Apply configured limits
input=$(cat)
file_size=$(echo "$input" | jq -r '.tool_input.content | length')
if [ "$file_size" -gt "$max_file_size" ]; then
echo '{"decision": "deny", "reason": "File exceeds configured size limit"}' >&2
exit 2
fi
```
**Configuration file (.claude/my-plugin.local.json):**
```json
{
"strictMode": true,
"maxFileSize": 500000,
"allowedPaths": ["/tmp", "/home/user/projects"]
}
```
**Use for:**
- User-configurable hook behavior
- Per-project settings
- Team-specific rules
- Dynamic validation criteria

View File

@@ -0,0 +1,164 @@
# Hook Development Utility Scripts
These scripts help validate, test, and lint hook implementations before deployment.
## validate-hook-schema.sh
Validates `hooks.json` configuration files for correct structure and common issues.
**Usage:**
```bash
./validate-hook-schema.sh path/to/hooks.json
```
**Checks:**
- Valid JSON syntax
- Required fields present
- Valid hook event names
- Proper hook types (command/prompt)
- Timeout values in valid ranges
- Hardcoded path detection
- Prompt hook event compatibility
**Example:**
```bash
cd my-plugin
./validate-hook-schema.sh hooks/hooks.json
```
## test-hook.sh
Tests individual hook scripts with sample input before deploying to Claude Code.
**Usage:**
```bash
./test-hook.sh [options] <hook-script> <test-input.json>
```
**Options:**
- `-v, --verbose` - Show detailed execution information
- `-t, --timeout N` - Set timeout in seconds (default: 60)
- `--create-sample <event-type>` - Generate sample test input
**Example:**
```bash
# Create sample test input
./test-hook.sh --create-sample PreToolUse > test-input.json
# Test a hook script
./test-hook.sh my-hook.sh test-input.json
# Test with verbose output and custom timeout
./test-hook.sh -v -t 30 my-hook.sh test-input.json
```
**Features:**
- Sets up proper environment variables (CLAUDE_PROJECT_DIR, CLAUDE_PLUGIN_ROOT)
- Measures execution time
- Validates output JSON
- Shows exit codes and their meanings
- Captures environment file output
## hook-linter.sh
Checks hook scripts for common issues and best practices violations.
**Usage:**
```bash
./hook-linter.sh <hook-script.sh> [hook-script2.sh ...]
```
**Checks:**
- Shebang presence
- `set -euo pipefail` usage
- Stdin input reading
- Proper error handling
- Variable quoting (injection prevention)
- Exit code usage
- Hardcoded paths
- Long-running code detection
- Error output to stderr
- Input validation
**Example:**
```bash
# Lint single script
./hook-linter.sh ../examples/validate-write.sh
# Lint multiple scripts
./hook-linter.sh ../examples/*.sh
```
## Typical Workflow
1. **Write your hook script**
```bash
vim my-plugin/scripts/my-hook.sh
```
2. **Lint the script**
```bash
./hook-linter.sh my-plugin/scripts/my-hook.sh
```
3. **Create test input**
```bash
./test-hook.sh --create-sample PreToolUse > test-input.json
# Edit test-input.json as needed
```
4. **Test the hook**
```bash
./test-hook.sh -v my-plugin/scripts/my-hook.sh test-input.json
```
5. **Add to hooks.json**
```bash
# Edit my-plugin/hooks/hooks.json
```
6. **Validate configuration**
```bash
./validate-hook-schema.sh my-plugin/hooks/hooks.json
```
7. **Test in Claude Code**
```bash
claude --debug
```
## Tips
- Always test hooks before deploying to avoid breaking user workflows
- Use verbose mode (`-v`) to debug hook behavior
- Check the linter output for security and best practice issues
- Validate hooks.json after any changes
- Create different test inputs for various scenarios (safe operations, dangerous operations, edge cases)
## Common Issues
### Hook doesn't execute
Check:
- Script has shebang (`#!/bin/bash`)
- Script is executable (`chmod +x`)
- Path in hooks.json is correct (use `${CLAUDE_PLUGIN_ROOT}`)
### Hook times out
- Reduce timeout in hooks.json
- Optimize hook script performance
- Remove long-running operations
### Hook fails silently
- Check exit codes (should be 0 or 2)
- Ensure errors go to stderr (`>&2`)
- Validate JSON output structure
### Injection vulnerabilities
- Always quote variables: `"$variable"`
- Use `set -euo pipefail`
- Validate all input fields
- Run the linter to catch issues

View File

@@ -0,0 +1,153 @@
#!/bin/bash
# Hook Linter
# Checks hook scripts for common issues and best practices
set -euo pipefail
# Usage
if [ $# -eq 0 ]; then
echo "Usage: $0 <hook-script.sh> [hook-script2.sh ...]"
echo ""
echo "Checks hook scripts for:"
echo " - Shebang presence"
echo " - set -euo pipefail usage"
echo " - Input reading from stdin"
echo " - Proper error handling"
echo " - Variable quoting"
echo " - Exit code usage"
echo " - Hardcoded paths"
echo " - Timeout considerations"
exit 1
fi
check_script() {
local script="$1"
local warnings=0
local errors=0
echo "🔍 Linting: $script"
echo ""
if [ ! -f "$script" ]; then
echo "❌ Error: File not found"
return 1
fi
# Check 1: Executable
if [ ! -x "$script" ]; then
echo "⚠️ Not executable (chmod +x $script)"
((warnings++))
fi
# Check 2: Shebang
first_line=$(head -1 "$script")
if [[ ! "$first_line" =~ ^#!/ ]]; then
echo "❌ Missing shebang (#!/bin/bash)"
((errors++))
fi
# Check 3: set -euo pipefail
if ! grep -q "set -euo pipefail" "$script"; then
echo "⚠️ Missing 'set -euo pipefail' (recommended for safety)"
((warnings++))
fi
# Check 4: Reads from stdin
if ! grep -q "cat\|read" "$script"; then
echo "⚠️ Doesn't appear to read input from stdin"
((warnings++))
fi
# Check 5: Uses jq for JSON parsing
if grep -q "tool_input\|tool_name" "$script" && ! grep -q "jq" "$script"; then
echo "⚠️ Parses hook input but doesn't use jq"
((warnings++))
fi
# Check 6: Unquoted variables
if grep -E '\$[A-Za-z_][A-Za-z0-9_]*[^"]' "$script" | grep -v '#' | grep -q .; then
echo "⚠️ Potentially unquoted variables detected (injection risk)"
echo " Always use double quotes: \"\$variable\" not \$variable"
((warnings++))
fi
# Check 7: Hardcoded paths
if grep -E '^[^#]*/home/|^[^#]*/usr/|^[^#]*/opt/' "$script" | grep -q .; then
echo "⚠️ Hardcoded absolute paths detected"
echo " Use \$CLAUDE_PROJECT_DIR or \$CLAUDE_PLUGIN_ROOT"
((warnings++))
fi
# Check 8: Uses CLAUDE_PLUGIN_ROOT
if ! grep -q "CLAUDE_PLUGIN_ROOT\|CLAUDE_PROJECT_DIR" "$script"; then
echo "💡 Tip: Use \$CLAUDE_PLUGIN_ROOT for plugin-relative paths"
fi
# Check 9: Exit codes
if ! grep -q "exit 0\|exit 2" "$script"; then
echo "⚠️ No explicit exit codes (should exit 0 or 2)"
((warnings++))
fi
# Check 10: JSON output for decision hooks
if grep -q "PreToolUse\|Stop" "$script"; then
if ! grep -q "permissionDecision\|decision" "$script"; then
echo "💡 Tip: PreToolUse/Stop hooks should output decision JSON"
fi
fi
# Check 11: Long-running commands
if grep -E 'sleep [0-9]{3,}|while true' "$script" | grep -v '#' | grep -q .; then
echo "⚠️ Potentially long-running code detected"
echo " Hooks should complete quickly (< 60s)"
((warnings++))
fi
# Check 12: Error messages to stderr
if grep -q 'echo.*".*error\|Error\|denied\|Denied' "$script"; then
if ! grep -q '>&2' "$script"; then
echo "⚠️ Error messages should be written to stderr (>&2)"
((warnings++))
fi
fi
# Check 13: Input validation
if ! grep -q "if.*empty\|if.*null\|if.*-z" "$script"; then
echo "💡 Tip: Consider validating input fields aren't empty"
fi
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $errors -eq 0 ] && [ $warnings -eq 0 ]; then
echo "✅ No issues found"
return 0
elif [ $errors -eq 0 ]; then
echo "⚠️ Found $warnings warning(s)"
return 0
else
echo "❌ Found $errors error(s) and $warnings warning(s)"
return 1
fi
}
echo "🔎 Hook Script Linter"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
total_errors=0
for script in "$@"; do
if ! check_script "$script"; then
((total_errors++))
fi
echo ""
done
if [ $total_errors -eq 0 ]; then
echo "✅ All scripts passed linting"
exit 0
else
echo "$total_errors script(s) had errors"
exit 1
fi

View File

@@ -0,0 +1,252 @@
#!/bin/bash
# Hook Testing Helper
# Tests a hook with sample input and shows output
set -euo pipefail
# Usage
show_usage() {
echo "Usage: $0 [options] <hook-script> <test-input.json>"
echo ""
echo "Options:"
echo " -h, --help Show this help message"
echo " -v, --verbose Show detailed execution information"
echo " -t, --timeout N Set timeout in seconds (default: 60)"
echo ""
echo "Examples:"
echo " $0 validate-bash.sh test-input.json"
echo " $0 -v -t 30 validate-write.sh write-input.json"
echo ""
echo "Creates sample test input with:"
echo " $0 --create-sample <event-type>"
exit 0
}
# Create sample input
create_sample() {
event_type="$1"
case "$event_type" in
PreToolUse)
cat <<'EOF'
{
"session_id": "test-session",
"transcript_path": "/tmp/transcript.txt",
"cwd": "/tmp/test-project",
"permission_mode": "ask",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/tmp/test.txt",
"content": "Test content"
}
}
EOF
;;
PostToolUse)
cat <<'EOF'
{
"session_id": "test-session",
"transcript_path": "/tmp/transcript.txt",
"cwd": "/tmp/test-project",
"permission_mode": "ask",
"hook_event_name": "PostToolUse",
"tool_name": "Bash",
"tool_result": "Command executed successfully"
}
EOF
;;
Stop|SubagentStop)
cat <<'EOF'
{
"session_id": "test-session",
"transcript_path": "/tmp/transcript.txt",
"cwd": "/tmp/test-project",
"permission_mode": "ask",
"hook_event_name": "Stop",
"reason": "Task appears complete"
}
EOF
;;
UserPromptSubmit)
cat <<'EOF'
{
"session_id": "test-session",
"transcript_path": "/tmp/transcript.txt",
"cwd": "/tmp/test-project",
"permission_mode": "ask",
"hook_event_name": "UserPromptSubmit",
"user_prompt": "Test user prompt"
}
EOF
;;
SessionStart|SessionEnd)
cat <<'EOF'
{
"session_id": "test-session",
"transcript_path": "/tmp/transcript.txt",
"cwd": "/tmp/test-project",
"permission_mode": "ask",
"hook_event_name": "SessionStart"
}
EOF
;;
*)
echo "Unknown event type: $event_type"
echo "Valid types: PreToolUse, PostToolUse, Stop, SubagentStop, UserPromptSubmit, SessionStart, SessionEnd"
exit 1
;;
esac
}
# Parse arguments
VERBOSE=false
TIMEOUT=60
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
show_usage
;;
-v|--verbose)
VERBOSE=true
shift
;;
-t|--timeout)
TIMEOUT="$2"
shift 2
;;
--create-sample)
create_sample "$2"
exit 0
;;
*)
break
;;
esac
done
if [ $# -ne 2 ]; then
echo "Error: Missing required arguments"
echo ""
show_usage
fi
HOOK_SCRIPT="$1"
TEST_INPUT="$2"
# Validate inputs
if [ ! -f "$HOOK_SCRIPT" ]; then
echo "❌ Error: Hook script not found: $HOOK_SCRIPT"
exit 1
fi
if [ ! -x "$HOOK_SCRIPT" ]; then
echo "⚠️ Warning: Hook script is not executable. Attempting to run with bash..."
HOOK_SCRIPT="bash $HOOK_SCRIPT"
fi
if [ ! -f "$TEST_INPUT" ]; then
echo "❌ Error: Test input not found: $TEST_INPUT"
exit 1
fi
# Validate test input JSON
if ! jq empty "$TEST_INPUT" 2>/dev/null; then
echo "❌ Error: Test input is not valid JSON"
exit 1
fi
echo "🧪 Testing hook: $HOOK_SCRIPT"
echo "📥 Input: $TEST_INPUT"
echo ""
if [ "$VERBOSE" = true ]; then
echo "Input JSON:"
jq . "$TEST_INPUT"
echo ""
fi
# Set up environment
export CLAUDE_PROJECT_DIR="${CLAUDE_PROJECT_DIR:-/tmp/test-project}"
export CLAUDE_PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(pwd)}"
export CLAUDE_ENV_FILE="${CLAUDE_ENV_FILE:-/tmp/test-env-$$}"
if [ "$VERBOSE" = true ]; then
echo "Environment:"
echo " CLAUDE_PROJECT_DIR=$CLAUDE_PROJECT_DIR"
echo " CLAUDE_PLUGIN_ROOT=$CLAUDE_PLUGIN_ROOT"
echo " CLAUDE_ENV_FILE=$CLAUDE_ENV_FILE"
echo ""
fi
# Run the hook
echo "▶️ Running hook (timeout: ${TIMEOUT}s)..."
echo ""
start_time=$(date +%s)
set +e
output=$(timeout "$TIMEOUT" bash -c "cat '$TEST_INPUT' | $HOOK_SCRIPT" 2>&1)
exit_code=$?
set -e
end_time=$(date +%s)
duration=$((end_time - start_time))
# Analyze results
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Results:"
echo ""
echo "Exit Code: $exit_code"
echo "Duration: ${duration}s"
echo ""
case $exit_code in
0)
echo "✅ Hook approved/succeeded"
;;
2)
echo "🚫 Hook blocked/denied"
;;
124)
echo "⏱️ Hook timed out after ${TIMEOUT}s"
;;
*)
echo "⚠️ Hook returned unexpected exit code: $exit_code"
;;
esac
echo ""
echo "Output:"
if [ -n "$output" ]; then
echo "$output"
echo ""
# Try to parse as JSON
if echo "$output" | jq empty 2>/dev/null; then
echo "Parsed JSON output:"
echo "$output" | jq .
fi
else
echo "(no output)"
fi
# Check for environment file
if [ -f "$CLAUDE_ENV_FILE" ]; then
echo ""
echo "Environment file created:"
cat "$CLAUDE_ENV_FILE"
rm -f "$CLAUDE_ENV_FILE"
fi
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $exit_code -eq 0 ] || [ $exit_code -eq 2 ]; then
echo "✅ Test completed successfully"
exit 0
else
echo "❌ Test failed"
exit 1
fi

View File

@@ -0,0 +1,159 @@
#!/bin/bash
# Hook Schema Validator
# Validates hooks.json structure and checks for common issues
set -euo pipefail
# Usage
if [ $# -eq 0 ]; then
echo "Usage: $0 <path/to/hooks.json>"
echo ""
echo "Validates hook configuration file for:"
echo " - Valid JSON syntax"
echo " - Required fields"
echo " - Hook type validity"
echo " - Matcher patterns"
echo " - Timeout ranges"
exit 1
fi
HOOKS_FILE="$1"
if [ ! -f "$HOOKS_FILE" ]; then
echo "❌ Error: File not found: $HOOKS_FILE"
exit 1
fi
echo "🔍 Validating hooks configuration: $HOOKS_FILE"
echo ""
# Check 1: Valid JSON
echo "Checking JSON syntax..."
if ! jq empty "$HOOKS_FILE" 2>/dev/null; then
echo "❌ Invalid JSON syntax"
exit 1
fi
echo "✅ Valid JSON"
# Check 2: Root structure
echo ""
echo "Checking root structure..."
VALID_EVENTS=("PreToolUse" "PostToolUse" "UserPromptSubmit" "Stop" "SubagentStop" "SessionStart" "SessionEnd" "PreCompact" "Notification")
for event in $(jq -r 'keys[]' "$HOOKS_FILE"); do
found=false
for valid_event in "${VALID_EVENTS[@]}"; do
if [ "$event" = "$valid_event" ]; then
found=true
break
fi
done
if [ "$found" = false ]; then
echo "⚠️ Unknown event type: $event"
fi
done
echo "✅ Root structure valid"
# Check 3: Validate each hook
echo ""
echo "Validating individual hooks..."
error_count=0
warning_count=0
for event in $(jq -r 'keys[]' "$HOOKS_FILE"); do
hook_count=$(jq -r ".\"$event\" | length" "$HOOKS_FILE")
for ((i=0; i<hook_count; i++)); do
# Check matcher exists
matcher=$(jq -r ".\"$event\"[$i].matcher // empty" "$HOOKS_FILE")
if [ -z "$matcher" ]; then
echo "$event[$i]: Missing 'matcher' field"
((error_count++))
continue
fi
# Check hooks array exists
hooks=$(jq -r ".\"$event\"[$i].hooks // empty" "$HOOKS_FILE")
if [ -z "$hooks" ] || [ "$hooks" = "null" ]; then
echo "$event[$i]: Missing 'hooks' array"
((error_count++))
continue
fi
# Validate each hook in the array
hook_array_count=$(jq -r ".\"$event\"[$i].hooks | length" "$HOOKS_FILE")
for ((j=0; j<hook_array_count; j++)); do
hook_type=$(jq -r ".\"$event\"[$i].hooks[$j].type // empty" "$HOOKS_FILE")
if [ -z "$hook_type" ]; then
echo "$event[$i].hooks[$j]: Missing 'type' field"
((error_count++))
continue
fi
if [ "$hook_type" != "command" ] && [ "$hook_type" != "prompt" ]; then
echo "$event[$i].hooks[$j]: Invalid type '$hook_type' (must be 'command' or 'prompt')"
((error_count++))
continue
fi
# Check type-specific fields
if [ "$hook_type" = "command" ]; then
command=$(jq -r ".\"$event\"[$i].hooks[$j].command // empty" "$HOOKS_FILE")
if [ -z "$command" ]; then
echo "$event[$i].hooks[$j]: Command hooks must have 'command' field"
((error_count++))
else
# Check for hardcoded paths
if [[ "$command" == /* ]] && [[ "$command" != *'${CLAUDE_PLUGIN_ROOT}'* ]]; then
echo "⚠️ $event[$i].hooks[$j]: Hardcoded absolute path detected. Consider using \${CLAUDE_PLUGIN_ROOT}"
((warning_count++))
fi
fi
elif [ "$hook_type" = "prompt" ]; then
prompt=$(jq -r ".\"$event\"[$i].hooks[$j].prompt // empty" "$HOOKS_FILE")
if [ -z "$prompt" ]; then
echo "$event[$i].hooks[$j]: Prompt hooks must have 'prompt' field"
((error_count++))
fi
# Check if prompt-based hooks are used on supported events
if [ "$event" != "Stop" ] && [ "$event" != "SubagentStop" ] && [ "$event" != "UserPromptSubmit" ] && [ "$event" != "PreToolUse" ]; then
echo "⚠️ $event[$i].hooks[$j]: Prompt hooks may not be fully supported on $event (best on Stop, SubagentStop, UserPromptSubmit, PreToolUse)"
((warning_count++))
fi
fi
# Check timeout
timeout=$(jq -r ".\"$event\"[$i].hooks[$j].timeout // empty" "$HOOKS_FILE")
if [ -n "$timeout" ] && [ "$timeout" != "null" ]; then
if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then
echo "$event[$i].hooks[$j]: Timeout must be a number"
((error_count++))
elif [ "$timeout" -gt 600 ]; then
echo "⚠️ $event[$i].hooks[$j]: Timeout $timeout seconds is very high (max 600s)"
((warning_count++))
elif [ "$timeout" -lt 5 ]; then
echo "⚠️ $event[$i].hooks[$j]: Timeout $timeout seconds is very low"
((warning_count++))
fi
fi
done
done
done
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $error_count -eq 0 ] && [ $warning_count -eq 0 ]; then
echo "✅ All checks passed!"
exit 0
elif [ $error_count -eq 0 ]; then
echo "⚠️ Validation passed with $warning_count warning(s)"
exit 0
else
echo "❌ Validation failed with $error_count error(s) and $warning_count warning(s)"
exit 1
fi

View File

@@ -0,0 +1,108 @@
---
name: kaggle-learner
description: This skill should be used when the user asks to "learn from Kaggle", "study Kaggle solutions", "analyze Kaggle competitions", or mentions Kaggle competition URLs. Provides access to extracted knowledge from winning Kaggle solutions across NLP, CV, time series, tabular, and multimodal domains.
version: 0.1.0
---
# Kaggle Learner
Extract and apply knowledge from Kaggle competition winning solutions. This skill provides access to a continuously updated knowledge base of techniques, code patterns, and best practices from top Kaggle competitors.
## Overview
Kaggle competitions are at the forefront of practical machine learning. Winning solutions often innovate with novel techniques, clever feature engineering, and optimized pipelines. This skill captures that knowledge and makes it accessible for your projects.
## When to Use
Use this skill when:
- Studying for a Kaggle competition
- Looking for proven techniques in a specific domain (NLP, CV, etc.)
- Need code templates for common ML tasks
- Want to learn from competition winners
## Knowledge Categories
| Category | Focus | Directory |
|----------|-------|-----------|
| **NLP** | Text classification, NER, translation, LLM applications | `references/knowledge/nlp/` |
| **CV** | Image classification, detection, segmentation, generation | `references/knowledge/cv/` |
| **Time Series** | Forecasting, anomaly detection, sequence modeling | `references/knowledge/time-series/` |
| **Tabular** | Feature engineering, traditional ML, structured data | `references/knowledge/tabular/` |
| **Multimodal** | Cross-modal tasks, vision-language models | `references/knowledge/multimodal/` |
**文件组织结构**:每个竞赛一个独立的 markdown 文件,按 domain 分类到对应目录。
示例:
- `time-series/birdclef-plus-2025.md`
- `nlp/aimo-2-2025.md`
## Quick Reference
**To learn from a competition:**
1. Provide the Kaggle competition URL
2. The kaggle-miner agent will extract the winning solution
3. Knowledge is automatically added to the relevant category
4. **前排方案详细技术分析** (Front-runner Detailed Technical Analysis) is automatically included
**To browse existing knowledge:**
- 浏览相关 domain 目录:`references/knowledge/[domain]/`
- 每个竞赛一个独立文件,包含:
- Competition Brief (竞赛简介)
- **前排方案详细技术分析** (前排方案详细技术分析) ⭐
- Code Templates (代码模板)
- Best Practices (最佳实践)
## Self-Evolving
This skill automatically updates its knowledge base when the kaggle-miner agent processes new competitions. The more you use it, the smarter it becomes.
## Knowledge Extraction Standard
每次从 Kaggle 竞赛提取知识时,**必须**包含以下标准部分:
### 必需内容清单
| 部分 | 说明 | 必需性 |
|------|------|--------|
| **Competition Brief** | 竞赛背景、任务描述、数据规模、评估指标 | ✅ 必需 |
| **Original Summaries** | 前排方案的简要概述 | ✅ 必需 |
| **前排方案详细技术分析** | Top 20 方案的核心技巧和实现细节 | ✅ **必需** ⭐ |
| **Code Templates** | 可复用的代码模板 | ✅ 必需 |
| **Best Practices** | 最佳实践和常见陷阱 | ✅ 必需 |
| **Metadata** | 数据源标签和日期 | ✅ 必需 |
### 前排方案详细技术分析格式
每个前排方案应包含:
- **排名和团队/作者**
- **核心技巧列表** (3-6 个关键技术点)
- **实现细节** (具体的参数、配置、数据)
示例格式:
```markdown
**排名 Place - 核心技术名称 (作者)**
核心技巧:
- **技巧1**: 简短说明
- **技巧2**: 简短说明
实现细节:
- 具体参数、模型、配置
- 数据和实验结果
```
**建议覆盖 Top 20 方案,获取更多前排选手的创新技巧**
## Additional Resources
### Knowledge Directories
- **`references/knowledge/nlp/`** - NLP competition techniques
- **`references/knowledge/cv/`** - Computer vision techniques
- **`references/knowledge/time-series/`** - Time series methods
- **`references/knowledge/tabular/`** - Tabular data approaches
- **`references/knowledge/multimodal/`** - Multimodal solutions
### Competition Examples
- **BirdCLEF+ 2025** (`time-series/birdclef-plus-2025.md`) - 包含完整的 Top 14 前排方案详细技术分析
- **BirdCLEF 2024** (`time-series/birdclef-2024.md`) - 包含 Top 3 方案详细技术分析
- **AIMO-2** (`nlp/aimo-2-2025.md`) - 包含 Top 12+ 前排方案技术总结

Some files were not shown because too many files have changed in this diff Show More