Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:40:02 +08:00
commit 0a8a6c982f
21 changed files with 4153 additions and 0 deletions

217
commands/docs/adr.md Normal file
View File

@@ -0,0 +1,217 @@
---
description: "Create numbered ADR documenting architectural decision"
argument-hint: "<title> [variant]"
allowed-tools: ["Read", "Write", "Grep", "Glob"]
---
# Create Architecture Decision Record
Create a new Architecture Decision Record (ADR) documenting an architectural decision.
## Your Task
1. **Parse Arguments**:
- Extract decision title from `$ARGUMENTS`
- Check for variant keyword: `lightweight`, `full`, or `madr`
- If variant found, remove it from title
- Default variant: `nygard` (Nygard style)
2. **Determine ADR Number**:
- Scan `docs/adr/` directory
- Find highest existing ADR number (format: `XXXX-*`)
- Increment by 1
- If no ADRs exist, start with `0001`
- Format as 4-digit padded number (e.g., `0001`, `0023`)
3. **Sanitize Title for Filename**:
- Convert title to kebab-case
- Remove special characters
- Lowercase all letters
- Example: "Use Redis for Caching" → `use-redis-for-caching`
4. **Gather Context**:
- Search codebase for relevant information about the decision topic
- Look for related code, configs, or documentation
- Understand current state and alternatives
- Keep context concise but informative
5. **Load Template**:
- Template location: `commands/docs/templates/adr/`
- Select based on variant:
- `nygard``nygard.md` (default)
- `lightweight``lightweight.md`
- `full``full.md`
- `madr``madr.md`
6. **Populate Template**:
Replace placeholders:
- `{{ADR_NUMBER}}` - 4-digit number
- `{{ADR_TITLE}}` - Original title (Title Case)
- `{{DATE}}` - Current date (YYYY-MM-DD)
- `{{CONTEXT}}` - Gathered context from codebase
- `{{PROJECT_NAME}}` - Git repo or directory name
7. **Create ADR File**:
- Filename: `docs/adr/XXXX-kebab-case-title.md`
- Ensure `docs/adr/` directory exists
- Write populated content
- Set initial status to "Proposed"
8. **Report Creation**:
- Show ADR number and title
- Display file path
- Provide next steps
## Template Variants
### Nygard Style (Default)
Michael Nygard's ADR format - concise and focused.
**Sections:**
- Title with number
- Status
- Context
- Decision
- Consequences
**Use when:** Most decisions, balanced detail
### Lightweight
Minimal ADR for quick decisions.
**Sections:**
- Title with number
- Status
- Decision
- Rationale
**Use when:** Simple, straightforward decisions
### Full
Comprehensive ADR with detailed sections.
**Sections:**
- Title with number
- Status
- Context
- Decision Drivers
- Considered Options
- Decision
- Consequences (Positive, Negative, Neutral)
- Pros and Cons
- Related Decisions
- References
**Use when:** Complex, high-impact decisions
### MADR
Markdown Architectural Decision Records format.
**Sections:**
- Title with number
- Status
- Context and Problem Statement
- Decision Drivers
- Considered Options
- Decision Outcome
- Consequences
**Use when:** Following MADR standard
## Usage
Basic ADR creation (uses Nygard template):
```
/docs:adr "Database Migration Strategy"
/docs:adr "API Authentication Approach"
/docs:adr "Microservices Communication Pattern"
```
With template variant override:
```
/docs:adr lightweight "Use Redis for Session Storage"
/docs:adr full "Adopt Event-Driven Architecture"
/docs:adr madr "Select Database Technology"
```
## ADR Numbering
- **First ADR**: `0001-record-architecture-decisions.md` (meta-ADR)
- **Subsequent ADRs**: Auto-incremented (0002, 0003, etc.)
- **Format**: `XXXX-kebab-case-title.md`
## ADR Status Lifecycle
Update status in the ADR as the decision progresses:
1. **Proposed** - Initial proposal (default)
2. **Accepted** - Decision approved
3. **Deprecated** - No longer recommended
4. **Superseded** - Replaced by another ADR
## Context Gathering Examples
```bash
# For database decisions
!`find . -name "*.sql" -o -name "*models.py" -o -name "*schema.prisma" | head -10`
# For API decisions
!`grep -r "router\|endpoint\|api" --include="*.py" --include="*.ts" --include="*.js" . | head -20`
# For architecture decisions
!`find . -name "docker-compose.yml" -o -name "*.config.js" -o -name "*.config.ts" | head -10`
```
## Important Notes
- **One Decision per ADR**: Keep focused on a single decision
- **Context Matters**: Include "why" even if it seems obvious
- **Link Related ADRs**: Reference superseded or related decisions
- **Early Documentation**: Create ADRs early in decision process
- **Imperative Language**: Use "we will" not "we should"
- **Status Updates**: Update status as decision progresses
## Example Output
```
Architecture Decision Record Created ✓
ADR-0006: Use Redis for Session Storage
File: docs/adr/0006-use-redis-for-session-storage.md
Status: Proposed
Template: Nygard Style
Next Steps:
1. Review and refine the decision context
2. Fill in consequences (positive/negative)
3. Discuss with team
4. Update status to "Accepted" when approved
5. Reference this ADR in related code/docs
```
## When to Create ADRs
Create an ADR when making:
- Technology stack decisions
- Architecture pattern choices
- Database or storage decisions
- API design choices
- Security architecture decisions
- Deployment strategy decisions
- Major library/framework selections
- Cross-cutting concerns (logging, caching, etc.)
## Best Practices
- **Create early**: Document decisions before implementation
- **Be honest**: Document the real reasons, not ideal reasons
- **Include alternatives**: Show what was considered
- **Accept trade-offs**: Acknowledge negative consequences
- **Link to code**: Reference implementation in the ADR
- **Review regularly**: Revisit ADRs during retrospectives
- **Update status**: Keep status current as decisions evolve
---
**Template Location**: `commands/docs/templates/adr/`
**Output Directory**: `docs/adr/`

268
commands/docs/check.md Normal file
View File

@@ -0,0 +1,268 @@
---
description: "Validate documentation freshness, completeness, and quality"
argument-hint: "[focus]"
allowed-tools: ["Read", "Grep", "Glob", "Bash(git *, find *)"]
---
# Check Documentation Quality
Validate documentation freshness, completeness, and quality against current codebase state.
## Your Task
1. **Parse Arguments**:
- Extract optional focus area from `$ARGUMENTS`
- Focus areas: `core`, `data`, `infrastructure`, `all`
- Default: check all documentation
2. **Scan Documentation**:
- Find all documentation files in `docs/`
- Identify documentation types present
- Check for ADRs and RFCs
3. **Analyze Project** (determine what docs should exist):
- Technology stack detection
- Database presence
- Deployment configurations
- Project type (library, app, service)
4. **Perform Validation Checks**:
**A. Relevance Check**:
- Determine which docs are relevant to this project
- Identify missing documentation for detected technologies
- Example: If database models found, should have data-model.md
**B. Freshness Check**:
- Compare doc last-modified dates with related code changes
- Use git to check recent changes:
```bash
# Check when files were last modified
!`git log -1 --format="%ai" -- docs/architecture.md 2>/dev/null`
# Check recent changes to codebase
!`git log --since="7 days ago" --oneline --name-only | head -50`
```
- Flag docs that haven't been updated after significant code changes
**C. Completeness Check**:
- Verify all required sections are present
- Check for unreplaced placeholders: `{{PLACEHOLDER}}`
- Ensure diagrams exist where expected
- Verify ADRs have all sections (Status, Context, Decision)
- Verify RFCs have all sections (Summary, Motivation, Proposal)
**D. Quality Check**:
- Validate Mermaid diagram syntax
- Check for broken internal links (references to non-existent files)
- Verify markdown formatting
- Check for empty sections
5. **Calculate Scores**:
**Freshness Scoring** (per document):
- Fresh (90-100): Updated within last 7 days or no related code changes
- Good (70-89): Minor code changes since last update
- Stale (50-69): Significant code changes since last update
- Outdated (<50): Major code changes or very old
**Completeness Scoring** (per document):
- Complete (90-100): All sections present, no placeholders
- Good (70-89): Most sections present, minor gaps
- Incomplete (50-69): Several missing sections
- Poor (<50): Major sections missing
**Quality Scoring** (per document):
- Excellent (90-100): No issues, all diagrams valid
- Good (70-89): Minor formatting issues
- Fair (50-69): Several issues
- Poor (<50): Major problems, broken diagrams
**Overall Score**:
- Average of all document scores
- Weight by importance (core docs > others)
6. **Generate Report**:
- Status summary with overall score
- List of documents by status (Good, Needs Attention, Missing)
- Quality issues with specific locations
- Actionable recommendations
## Validation Checks Detail
### Missing Documentation
```bash
# Check for expected docs
!`ls -1 docs/ 2>/dev/null | grep -E "architecture|onboarding|data-model|deployment"`
# Check for ADRs
!`ls -1 docs/adr/*.md 2>/dev/null | wc -l`
# Check for RFCs
!`ls -1 docs/rfc/*.md 2>/dev/null | wc -l`
```
### Stale Documentation
```bash
# Get last modification date of docs
!`find docs -name "*.md" -exec stat -f "%Sm %N" -t "%Y-%m-%d" {} \; 2>/dev/null || find docs -name "*.md" -exec stat -c "%y %n" {} \;`
# Get recent code changes
!`git log --since="30 days ago" --name-only --pretty=format: | sort -u | grep -v "^$" | head -30`
```
### Placeholder Check
```bash
# Find unreplaced placeholders
!`grep -r "{{.*}}" docs/ --include="*.md" 2>/dev/null`
```
### Broken Links
```bash
# Find markdown links
!`grep -r "\[.*\](" docs/ --include="*.md" -h | grep -o "\[.*\](.*)" | head -20`
```
## Usage
Check all documentation:
```
/docs:check
```
With specific focus:
```
/docs:check core
/docs:check data
/docs:check focus on database documentation
```
Quick check:
```
/docs:check quick
```
## Output Format
### Status Summary
```
Documentation Health Report
Overall Score: 85/100
✅ Good (3 docs):
• docs/architecture.md (Score: 95/100)
- Last updated: 2 days ago
- All sections complete
- Diagrams valid
• docs/onboarding.md (Score: 92/100)
- Last updated: 1 week ago
- Comprehensive and current
• docs/adr/ (5 records, Score: 88/100)
- All ADRs properly formatted
- Recent decisions documented
⚠️ Needs Attention (2 docs):
• docs/data-model.md (Score: 65/100)
- Outdated: Models changed 5 days ago (docs/data-model.md:1)
- Missing ER diagram
→ Recommendation: Run /docs:diagram er
• docs/deployment.md (Score: 58/100)
- Missing deployment steps for new services
- Placeholder not replaced: {{DEPLOYMENT_STEPS}} (line 42)
→ Recommendation: Run /docs:update deployment
❌ Missing (2 docs):
• docs/security.md
- Security middleware detected but not documented
→ Recommendation: Run /docs:init or /docs:diagram security
• docs/api-documentation.md
- 15 API endpoints found but not documented
→ Recommendation: Run /docs:init
🔧 Quality Issues:
• docs/data-model.md:42 - Invalid Mermaid syntax
• docs/architecture.md:15 - Broken link to [non-existent.md]
• docs/deployment.md:23 - Unreplaced placeholder {{DEPLOYMENT_STEPS}}
```
### Detailed Report
For each documentation file:
- **Filename and path**
- **Score breakdown** (Freshness + Completeness + Quality)
- **Last Updated**: Timestamp
- **Specific Issues**: With line numbers
- **Recommendations**: Actionable next steps with commands
## Recommendations Format
Based on findings, suggest specific actions:
```
Priority Recommendations:
1. HIGH: Update data model documentation
Command: /docs:diagram er
Reason: Schema changed 5 days ago, ER diagram missing
2. MEDIUM: Fix deployment documentation placeholders
Command: /docs:update deployment
Reason: Contains unreplaced placeholders
3. LOW: Add security documentation
Command: /docs:diagram security
Reason: Good practice for complete documentation
```
## Important Notes
- **Non-destructive**: Only reads, never modifies documentation
- **Git-aware**: Uses git history to assess freshness
- **Context-aware**: Understands project type and relevant docs
- **Actionable**: Provides specific commands to fix issues
- **Incremental**: Can be run frequently
## Example Checks
### Core Documentation
- architecture.md exists and current?
- onboarding.md exists and comprehensive?
- ADRs directory exists with properly formatted ADRs?
### Data Documentation
- data-model.md exists if database detected?
- ER diagrams present and valid?
- Schema matches current models?
### Infrastructure Documentation
- deployment.md exists if Docker/K8s detected?
- Security.md exists?
- Dependencies documented?
## When to Run
Run this command:
- Before onboarding new team members
- During documentation reviews
- After major refactoring
- As part of pre-release checklist
- When documentation feels stale
- Regularly (weekly or bi-weekly)
## Best Practices
- **Run regularly**: Make it part of your workflow
- **Address issues**: Don't let documentation debt accumulate
- **Automate**: Consider running in CI for documentation PRs
- **Prioritize**: Fix high-impact issues first
- **Track scores**: Monitor documentation health over time
---
**Dependencies**: Requires git for freshness checking
**Output**: Comprehensive health report with scores and recommendations

327
commands/docs/diagram.md Normal file
View File

@@ -0,0 +1,327 @@
---
description: "Generate Mermaid diagrams from codebase analysis"
argument-hint: "<type> [context]"
allowed-tools: ["Read", "Write", "Grep", "Glob"]
---
# Generate System Diagrams
Generate Mermaid diagrams including architecture, database schema, deployment, and security architecture.
## Your Task
1. **Parse Arguments**:
- Extract diagram type from `$ARGUMENTS`
- Supported types: `er`, `arch`, `deployment`, `security`
- Extract optional context (remaining arguments)
2. **Validate Diagram Type**:
- If type not provided or invalid, show available types
- Exit with helpful message
3. **Analyze Codebase** (based on diagram type):
**For ER Diagrams (`er`)**:
- Find ORM model files
- Supported ORMs:
- Python: SQLAlchemy, Django, Tortoise, SQLModel, Peewee
- JS/TS: Prisma, TypeORM, Sequelize, Mongoose
- Other: GORM (Go), ActiveRecord (Ruby)
- Extract:
- Tables/entities
- Columns with types
- Relationships (one-to-one, one-to-many, many-to-many)
- Constraints (PK, FK, unique)
**For Architecture Diagrams (`arch`)**:
- Identify major components
- Find services, APIs, workers
- Detect queues, caches, databases
- Map data flow between components
- Identify external dependencies
**For Deployment Diagrams (`deployment`)**:
- Find deployment configs (docker-compose, k8s, etc.)
- Identify services and their relationships
- Map CI/CD pipeline
- Document environment configurations
**For Security Diagrams (`security`)**:
- Find authentication/authorization code
- Map security boundaries
- Identify data encryption points
- Document security controls
4. **Generate Mermaid Diagram**:
- Create appropriate Mermaid syntax based on type
- Include meaningful labels and relationships
- Add comments for clarity
- Keep diagram readable (not too complex)
5. **Load Template**:
- Template location: `commands/docs/templates/`
- Select based on diagram type:
- `er``data-model.md`
- `arch``architecture.md`
- `deployment``deployment.md`
- `security``security.md`
6. **Populate Template**:
Replace placeholders:
- `{{PROJECT_NAME}}` - Git repo or directory name
- `{{DATE}}` - Current date
- `{{ER_DIAGRAM}}` or `{{DIAGRAM_CONTENT}}` - Generated Mermaid code
- `{{ENTITIES}}` or `{{COMPONENTS}}` - Entity/component descriptions
- Other diagram-specific placeholders
7. **Create or Update Documentation**:
- Output to appropriate file in `docs/`
- If file exists, ask before overwriting
- Preserve custom content if possible
8. **Report Results**:
- Show diagram type and output file
- Display summary of what was detected
- Provide next steps
## Supported Diagram Types
### ER Diagram (`er`)
**Output**: `docs/data-model.md`
Entity-Relationship diagram from database models.
**Detects**:
- Tables and entities
- Columns with data types
- Primary keys
- Foreign keys
- Relationships
- Constraints
**Mermaid syntax**:
```mermaid
erDiagram
USER ||--o| PROFILE : "has"
USER {
uuid id PK
string email UK
string password_hash
}
PROFILE {
uuid id PK
uuid user_id FK
string bio
}
```
### Architecture Diagram (`arch`)
**Output**: `docs/architecture.md`
System architecture and component relationships.
**Detects**:
- Services and modules
- API endpoints
- Databases
- Caches
- Message queues
- External services
**Mermaid syntax**:
```mermaid
graph TB
Client[Web Client]
API[API Server]
DB[(Database)]
Cache[(Redis)]
Client --> API
API --> DB
API --> Cache
```
### Deployment Diagram (`deployment`)
**Output**: `docs/deployment.md`
Deployment infrastructure and CI/CD.
**Detects**:
- Docker containers
- Kubernetes resources
- Cloud services
- CI/CD pipeline stages
- Environment configurations
**Mermaid syntax**:
```mermaid
graph LR
Dev[Development]
CI[CI Pipeline]
Stage[Staging]
Prod[Production]
Dev --> CI
CI --> Stage
Stage --> Prod
```
### Security Diagram (`security`)
**Output**: `docs/security.md`
Security architecture and data flow.
**Detects**:
- Authentication flows
- Authorization boundaries
- Encryption points
- Security controls
- Trust boundaries
**Mermaid syntax**:
```mermaid
graph TB
User[User]
Auth[Auth Service]
API[Protected API]
DB[(Encrypted DB)]
User -->|JWT| Auth
Auth -->|Validated| API
API -->|TLS| DB
```
## Usage
Generate specific diagram type:
```
/docs:diagram er
/docs:diagram arch
/docs:diagram deployment
/docs:diagram security
```
With additional context:
```
/docs:diagram er for user and order tables
/docs:diagram arch for microservices architecture
/docs:diagram deployment with Docker and Kubernetes
```
Show available types:
```
/docs:diagram
```
## ORM Detection Examples
### Python ORMs
```bash
# SQLAlchemy
!`find . -name "*models.py" -exec grep -l "Base\|Column\|relationship" {} \; | head -10`
# Django
!`find . -name "models.py" -exec grep -l "models.Model" {} \; | head -10`
# Tortoise ORM
!`find . -name "*.py" -exec grep -l "tortoise.models" {} \; | head -10`
```
### JavaScript/TypeScript ORMs
```bash
# Prisma
!`find . -name "schema.prisma"`
# TypeORM
!`find . -name "*.entity.ts" -o -name "*entity.js" | head -10`
# Sequelize
!`find . -name "*.model.js" -o -name "*.model.ts" | head -10`
```
## Architecture Detection Examples
```bash
# Find services
!`find . -name "*service*.ts" -o -name "*service*.py" -o -name "*service*.js" | head -15`
# Find API routes
!`find . -name "*router*.ts" -o -name "*routes*.py" -o -name "*controller*.js" | head -15`
# Find configs
!`find . -name "*.config.js" -o -name "*.config.ts" -o -name "config.py" | head -10`
```
## Deployment Detection Examples
```bash
# Docker
!`find . -name "Dockerfile" -o -name "docker-compose.yml" -o -name "docker-compose.yaml"`
# Kubernetes
!`find . -name "*.k8s.yaml" -o -name "*.k8s.yml" -o -name "*deployment.yaml"`
# CI/CD
!`find . -name ".github/workflows/*.yml" -o -name ".gitlab-ci.yml" -o -name "Jenkinsfile"`
```
## Important Notes
- **Auto-detection**: Diagrams generated from actual code
- **Mermaid format**: Uses GitHub-compatible Mermaid syntax
- **Readable diagrams**: Limits complexity for clarity
- **Incremental**: Can regenerate as code evolves
- **Template-based**: Uses templates for consistent formatting
- **Context-aware**: Uses optional context to guide generation
## Example Output
```
ER Diagram Generated ✓
Detected: 5 entities, 12 relationships
File: docs/data-model.md
Entities Found:
✓ User (SQLAlchemy model)
✓ Profile (SQLAlchemy model)
✓ Role (SQLAlchemy model)
✓ Permission (SQLAlchemy model)
✓ UserRole (junction table)
Relationships:
✓ User → Profile (one-to-one)
✓ User → UserRole (one-to-many)
✓ Role → UserRole (one-to-many)
✓ Role → Permission (many-to-many)
Next Steps:
1. Review generated ER diagram
2. Add entity descriptions if needed
3. Update when schema changes
4. Reference in architecture docs
```
## When to Run
Run when:
- Database schema has been modified (`er`)
- Architecture has evolved (`arch`)
- Deployment configuration changed (`deployment`)
- Security architecture modified (`security`)
- Onboarding new team members (all diagrams)
- Documentation review (all diagrams)
## Best Practices
- **Keep current**: Regenerate after significant changes
- **Review generated**: Always review auto-generated content
- **Add context**: Supplement with manual descriptions
- **Link diagrams**: Reference diagrams in related docs
- **Version control**: Commit diagram updates with code changes
- **Simplify**: Break complex diagrams into multiple views
---
**Template Location**: `commands/docs/templates/`
**Output Directory**: `docs/`

155
commands/docs/init.md Normal file
View File

@@ -0,0 +1,155 @@
---
description: "Initialize comprehensive documentation structure for project"
argument-hint: "[context]"
allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash(git *)"]
---
# Initialize Project Documentation
Generate comprehensive documentation structure for your project based on detected technologies and configuration.
## Your Task
1. **Detect Project Characteristics**:
- Technology stack (language, frameworks, databases)
- Project type (web app, CLI, library, microservice, etc.)
- Infrastructure (Docker, K8s, cloud configs)
- Database/ORM presence (SQLAlchemy, Prisma, TypeORM, Django, etc.)
2. **Determine Relevant Documentation**:
- **Core Documentation** (always generate):
- `docs/architecture.md` - System architecture overview
- `docs/onboarding.md` - Developer onboarding guide
- `docs/adr/0001-record-architecture-decisions.md` - First ADR (meta-ADR)
- **Data Documentation** (if database detected):
- `docs/data-model.md` - Database schema & ER diagrams
- **Infrastructure Documentation** (if deployment configs found):
- `docs/deployment.md` - CI/CD & deployment procedures
- `docs/security.md` - Security architecture
- **Development Documentation** (if collaborative project):
- `docs/contributing.md` - Contribution guidelines
- `docs/rfc/` - RFC directory for proposals
3. **Check for Existing Documentation**:
- Scan `docs/` directory
- If files exist, ask user before overwriting
- Show what will be created vs what exists
4. **Load Templates**:
- Templates are in `commands/docs/templates/`
- Use appropriate template for each document type
- Replace placeholders with project-specific values
5. **Generate Documentation**:
- Create `docs/` directory if it doesn't exist
- Create subdirectories: `docs/adr/`, `docs/rfc/` (if needed)
- Generate each relevant documentation file
- Populate with project-specific content
6. **Template Placeholders**:
Replace these in templates:
- `{{PROJECT_NAME}}` - From git repo name or directory name
- `{{DATE}}` - Current date (YYYY-MM-DD format)
- `{{TECH_STACK}}` - Detected technologies
- `{{DESCRIPTION}}` - Brief project description from README or git
- `{{CONTEXT}}` - Gathered context from codebase analysis
7. **Report Results**:
- List all documentation files created
- Show what was skipped (already exists)
- Provide next steps
## Context Detection Examples
### Technology Stack
```bash
# Check for language/framework
!`find . -name "package.json" -o -name "pyproject.toml" -o -name "go.mod" -o -name "Cargo.toml" | head -5`
# Check for database
!`find . -name "*models.py" -o -name "*schema.prisma" -o -name "*entity.ts" | head -5`
# Check for infrastructure
!`find . -name "Dockerfile" -o -name "docker-compose.yml" -o -name "*.k8s.yaml" | head -5`
```
### Project Information
```bash
# Get project name
!`basename $(git rev-parse --show-toplevel 2>/dev/null || pwd)`
# Get project description
!`head -20 README.md 2>/dev/null || echo ""`
```
## Usage
Basic initialization (auto-detect everything):
```
/docs:init
```
With additional context:
```
/docs:init for Python FastAPI microservice
/docs:init for Next.js SaaS application
/docs:init for React component library
```
## Template Locations
Templates are loaded from `commands/docs/templates/`:
| Document Type | Template File |
|--------------|---------------|
| Architecture | `architecture.md` |
| Onboarding | `onboarding.md` |
| ADR (first) | `adr/nygard.md` |
| Data Model | `data-model.md` |
| Deployment | `deployment.md` |
| Security | `security.md` |
| Contributing | `contributing.md` |
## Important Notes
- **Zero-config**: Works without any configuration file
- **Smart detection**: Only generates relevant documentation
- **Safe**: Always asks before overwriting existing files
- **Customizable**: User context in command is used to enhance generation
- **Git-aware**: Uses git information when available
- **Incremental**: Can be run multiple times safely
## Example Output
```
Documentation Initialization Complete ✓
Created:
✓ docs/architecture.md - System architecture overview
✓ docs/onboarding.md - Developer onboarding guide
✓ docs/adr/0001-record-architecture-decisions.md - Meta-ADR
✓ docs/data-model.md - Database schema (SQLAlchemy detected)
✓ docs/deployment.md - Deployment guide (Docker detected)
Skipped (already exists):
⊘ docs/contributing.md
Next Steps:
1. Review and customize generated documentation
2. Run /docs:diagram er to generate ER diagram
3. Run /docs:diagram arch to generate architecture diagram
4. Create ADRs for key decisions: /docs:adr "Decision Title"
```
## When to Run
Run this command when:
- Starting a new project
- Adding documentation to an existing project
- Reorganizing project documentation
- Onboarding new team members
**Note**: You can run this command multiple times. It will only create missing files and ask before overwriting existing ones.

258
commands/docs/rfc.md Normal file
View File

@@ -0,0 +1,258 @@
---
description: "Create numbered RFC for proposing and discussing changes"
argument-hint: "<title> [variant]"
allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash(git *)"]
---
# Create Request For Comments
Create a new RFC (Request For Comments) document for proposing and discussing changes.
## Your Task
1. **Parse Arguments**:
- Extract proposal title from `$ARGUMENTS`
- Check for variant keyword: `minimal`, `standard`, or `detailed`
- If variant found, remove it from title
- Default variant: `standard`
2. **Determine RFC Number**:
- Scan `docs/rfc/` directory
- Find highest existing RFC number (format: `RFC-XXXX-*`)
- Increment by 1
- If no RFCs exist, start with `0001`
- Format as 4-digit padded number (e.g., `0001`, `0023`)
3. **Sanitize Title for Filename**:
- Convert title to kebab-case
- Remove special characters
- Lowercase all letters
- Example: "Add GraphQL API Support" → `add-graphql-api-support`
4. **Gather Context**:
- Analyze codebase to understand current state
- Identify relevant files and patterns
- Find similar implementations or related features
- Understand technical constraints
5. **Get Author Information**:
```bash
# Try to get git author
!`git config user.name 2>/dev/null || echo "Development Team"`
```
6. **Load Template**:
- Template location: `commands/docs/templates/rfc/`
- Select based on variant:
- `minimal` → `minimal.md`
- `standard` → `standard.md` (default)
- `detailed` → `detailed.md`
7. **Populate Template**:
Replace placeholders:
- `{{RFC_NUMBER}}` - 4-digit number
- `{{RFC_TITLE}}` - Original title (Title Case)
- `{{DATE}}` - Current date (YYYY-MM-DD)
- `{{AUTHOR}}` - Git user name or "Development Team"
- `{{CONTEXT}}` - Gathered context from codebase
- `{{PROJECT_NAME}}` - Git repo or directory name
8. **Create RFC File**:
- Filename: `docs/rfc/RFC-XXXX-kebab-case-title.md`
- Ensure `docs/rfc/` directory exists
- Write populated content
- Set initial status to "Draft"
9. **Report Creation**:
- Show RFC number and title
- Display file path
- Provide workflow guidance
## Template Variants
### Minimal Template
Quick proposal format for small changes.
**Sections:**
- Summary
- Motivation
- Proposal
- Open Questions
**Use when:** Small features, minor changes
### Standard Template (Default)
Balanced RFC for most changes.
**Sections:**
- Summary
- Motivation
- Proposal
- Rationale and Alternatives
- Implementation Plan
- Testing Plan
- Migration Strategy
- Open Questions
- Timeline
**Use when:** Most feature proposals
### Detailed Template
Comprehensive RFC for major changes.
**Sections:**
- Summary
- Background and Motivation
- Goals and Non-Goals
- Proposal
- Detailed Design
- Rationale and Alternatives
- Implementation Plan
- Testing and Quality Assurance
- Migration and Rollout Strategy
- Monitoring and Metrics
- Security Considerations
- Performance Implications
- Open Questions and Risks
- Timeline and Milestones
- Appendices
**Use when:** Major features, architectural changes
## Usage
Basic RFC creation (uses Standard template):
```
/docs:rfc "Add GraphQL API Support"
/docs:rfc "Implement Rate Limiting"
/docs:rfc "Add Multi-Tenancy Support"
```
With template variant override:
```
/docs:rfc minimal "Update Logging Format"
/docs:rfc detailed "Migration to Microservices Architecture"
/docs:rfc detailed "Adopt Event Sourcing Pattern"
```
## RFC Status Lifecycle
Update status in the RFC as it progresses:
1. **Draft** - Initial proposal, gathering feedback
2. **In Review** - Under discussion, modifications being made
3. **Accepted** - Approved for implementation
4. **Implemented** - Changes have been deployed
5. **Rejected** - Not moving forward with proposal
6. **Withdrawn** - Author withdrew the proposal
## RFC Workflow
### 1. Create RFC
```
/docs:rfc "Proposal Title"
```
### 2. Initial Draft
- Write comprehensive proposal
- Include motivation and context
- Document alternatives considered
- Add implementation plan
### 3. Share for Feedback
- Share RFC with team
- Update status to "In Review"
- Collect feedback in comments or discussions
### 4. Iterate
- Incorporate feedback
- Update proposal as needed
- Address concerns and questions
- Refine implementation details
### 5. Final Decision
- Stakeholders review final version
- Update status to "Accepted" or "Rejected"
- Document decision rationale
### 6. Implementation
- Reference RFC in PRs
- Update RFC with implementation notes
- Mark status as "Implemented" when complete
## Context Gathering Examples
```bash
# For API changes
!`find . -name "*router*" -o -name "*controller*" -o -name "*api*" | head -10`
# For feature additions
!`grep -r "export.*function\|export.*class" --include="*.ts" --include="*.js" . | head -20`
# For infrastructure changes
!`find . -name "*.yml" -o -name "*.yaml" -o -name "Dockerfile" | head -10`
# For performance changes
!`grep -r "cache\|redis\|memcache\|performance" --include="*.py" --include="*.ts" . | head -15`
```
## Important Notes
- **Write Before Implementing**: Create RFCs before starting work
- **Concrete Examples**: Include real code examples when possible
- **Address Concerns**: Proactively address potential objections
- **Update Actively**: RFC is a living document during review
- **Link Related Work**: Reference ADRs, issues, or other RFCs
- **Clear Language**: Keep accessible to all stakeholders
- **Define Success**: Include measurable success criteria
## Example Output
```
Request For Comments Created ✓
RFC-0003: Add GraphQL API Support
File: docs/rfc/RFC-0003-add-graphql-api-support.md
Status: Draft
Template: Standard
Author: Jane Developer
Next Steps:
1. Complete the proposal sections
2. Add implementation timeline
3. Document testing strategy
4. Share with team for feedback
5. Update status to "In Review"
6. Address feedback and iterate
7. Get stakeholder approval
```
## When to Create RFCs
Create an RFC when proposing:
- Major feature additions
- Significant refactorings
- Architecture changes
- Breaking API changes
- New technology adoptions
- Process changes
- Performance optimizations with trade-offs
- Security enhancements
- Developer experience improvements
## Best Practices
- **Early Documentation**: Write RFC before implementation
- **Be Specific**: Include concrete examples and details
- **Show Your Work**: Document research and investigation
- **Consider Alternatives**: Show what else was considered and why
- **Realistic Timeline**: Include reasonable milestones
- **Risk Assessment**: Document known risks and mitigation
- **Stakeholder Input**: Identify who should review
- **Clear Outcomes**: Define what success looks like
- **Keep Updated**: Reflect changes made during review
---
**Template Location**: `commands/docs/templates/rfc/`
**Output Directory**: `docs/rfc/`

308
commands/docs/update.md Normal file
View File

@@ -0,0 +1,308 @@
---
description: "Update documentation by syncing with current codebase state"
argument-hint: "[all|<doc-name>|category:<name>]"
allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash(git *)"]
---
# Update Documentation
Synchronize documentation with the current codebase state. Can update all docs, specific files, or entire categories.
## Your Task
1. **Parse Arguments**:
- Extract update mode from `$ARGUMENTS`
- Modes:
- No args or `all` → Update all relevant docs
- `<doc-name>` → Update specific doc (e.g., `architecture`)
- `category:<name>` → Update category (e.g., `category:data`)
- Default: Update all
2. **Determine Update Scope**:
**For "all" mode**:
- Analyze entire project
- Identify all relevant documentation types
- Update everything that exists or should exist
**For specific doc mode**:
- Validate doc name
- Find the corresponding file
- Update only that document
**For category mode**:
- Parse category name: `core`, `data`, `infrastructure`, `development`
- Identify all docs in that category
- Update all docs in the category
3. **Analyze Codebase**:
- Detect technology stack
- Find database models (for data docs)
- Find deployment configs (for infrastructure docs)
- Identify services and components (for architecture)
- Check for recent code changes
4. **Check Documentation Freshness**:
```bash
# For each doc, compare with related code changes
!`git log --since="$(git log -1 --format=%ai docs/architecture.md)" --oneline --name-only | head -30`
```
- Identify which docs are outdated
- Prioritize updates
5. **Load Templates**:
- Template location: `commands/docs/templates/`
- Load appropriate templates based on docs being updated
6. **Update Each Document**:
- Re-analyze relevant parts of codebase
- Regenerate diagrams if needed
- Update content while preserving custom sections
- Replace placeholders with current values
7. **Preserve Custom Content** (Important):
- Keep manually added sections
- Preserve non-template content
- Only update auto-generated parts
- If unsure, ask before overwriting
8. **Report Results**:
- List documents updated
- List documents skipped (up to date)
- List documents created (if missing)
- Show summary of changes
## Documentation Categories
### Core Documentation
Files that are always relevant:
- `docs/architecture.md` - System architecture
- `docs/onboarding.md` - Developer onboarding
- `docs/adr/` - Architecture Decision Records
**Update when**: Architecture changes, setup process changes
### Data Documentation
Files relevant if database detected:
- `docs/data-model.md` - Database schema & ER diagrams
**Update when**: Schema changes, models modified
### Infrastructure Documentation
Files relevant if deployment configs detected:
- `docs/deployment.md` - CI/CD & deployment
- `docs/security.md` - Security architecture
**Update when**: Infrastructure changes, security updates
### Development Documentation
Files relevant for collaborative projects:
- `docs/contributing.md` - Contribution guidelines
- `docs/rfc/` - RFC documents
- `docs/api-documentation.md` - API documentation
**Update when**: Process changes, API changes
## Usage
Update all documentation:
```
/docs:update
/docs:update all
```
Update specific document:
```
/docs:update architecture
/docs:update data-model
/docs:update onboarding
/docs:update deployment
/docs:update security
```
Update entire category:
```
/docs:update category:core
/docs:update category:data
/docs:update category:infrastructure
/docs:update category:development
```
With context:
```
/docs:update architecture after microservices refactor
/docs:update data-model after schema migration
/docs:update category:core for onboarding review
```
## Document Name Mapping
| Argument | File Path |
|----------------|----------------------------|
| `architecture` | `docs/architecture.md` |
| `onboarding` | `docs/onboarding.md` |
| `data-model` | `docs/data-model.md` |
| `deployment` | `docs/deployment.md` |
| `security` | `docs/security.md` |
| `contributing` | `docs/contributing.md` |
| `api-docs` | `docs/api-documentation.md`|
## Update Process Detail
### For Architecture Documentation
1. Scan for services, modules, components
2. Identify databases, caches, queues
3. Map data flow
4. Generate architecture diagram
5. Update component descriptions
6. Preserve custom architecture notes
### For Data Model Documentation
1. Find ORM models
2. Extract entities and relationships
3. Generate ER diagram
4. Document constraints
5. Update entity descriptions
6. Preserve custom data notes
### For Deployment Documentation
1. Find Docker/K8s configs
2. Map services to infrastructure
3. Document CI/CD pipeline
4. Update environment configurations
5. Preserve custom deployment notes
### For Security Documentation
1. Find auth/authz code
2. Map security boundaries
3. Document encryption points
4. Identify security controls
5. Preserve custom security notes
## Change Detection
```bash
# Check what changed since last doc update
!`git log --since="$(git log -1 --format=%ai docs/architecture.md 2>/dev/null || echo '30 days ago')" --oneline`
# Find modified source files
!`git diff --name-only HEAD@{7.days.ago}..HEAD 2>/dev/null | grep -E "\.(py|ts|js|java|go)$" | head -20`
# Check for new files
!`git log --since="7 days ago" --diff-filter=A --name-only --pretty=format: | sort -u | head -20`
```
## Template Placeholder Replacement
Replace these placeholders during update:
- `{{PROJECT_NAME}}` - Current project name
- `{{DATE}}` - Current date
- `{{TECH_STACK}}` - Detected technologies
- `{{ER_DIAGRAM}}` - Generated ER diagram
- `{{ARCHITECTURE_DIAGRAM}}` - Generated architecture diagram
- `{{ENTITIES}}` - Extracted entity descriptions
- `{{COMPONENTS}}` - Extracted component descriptions
## Important Notes
- **Preserves custom content**: Doesn't blindly overwrite
- **Smart updates**: Only updates outdated sections
- **Diagram regeneration**: Auto-regenerates diagrams
- **Git-aware**: Uses git to detect what changed
- **Safe**: Asks before major changes
- **Incremental**: Can be run frequently
## Example Output
### All Docs Update
```
Documentation Update Complete ✓
Updated (4 docs):
✓ docs/architecture.md (new microservices added)
✓ docs/data-model.md (schema changed, ER diagram regenerated)
✓ docs/deployment.md (K8s config updated)
✓ docs/adr/ (meta-ADR updated)
Up to Date (2 docs):
• docs/onboarding.md (no changes needed)
• docs/security.md (no changes needed)
Created (1 doc):
+ docs/contributing.md (collaborative project detected)
Changes Summary:
- 3 diagrams regenerated
- 12 sections updated
- 1 new document created
- 0 manual sections affected
```
### Specific Doc Update
```
Architecture Documentation Updated ✓
File: docs/architecture.md
Changes:
✓ Added 2 new services (AuthService, NotificationService)
✓ Updated architecture diagram
✓ Documented new message queue integration
✓ Preserved custom deployment notes
Detected:
- 5 services total
- 3 databases (PostgreSQL, Redis, MongoDB)
- 2 message queues (RabbitMQ, Kafka)
- 8 external API integrations
Diagram: Updated with latest component relationships
```
### Category Update
```
Core Documentation Category Updated ✓
Updated (3 docs):
✓ docs/architecture.md
✓ docs/onboarding.md
✓ docs/adr/ (5 records)
Changes:
- Architecture: Added microservices diagram
- Onboarding: Updated setup instructions for new tooling
- ADRs: Verified all properly formatted
Next Steps:
1. Review updated documentation
2. Consider updating diagrams: /docs:diagram arch
3. Create new ADR for recent decision: /docs:adr "Decision Title"
```
## When to Run
Run this command:
- After major refactoring
- When database schema changes
- After adding new features or components
- Before onboarding new team members
- When documentation becomes stale
- As part of release process
- After infrastructure changes
- Before documentation reviews
## Best Practices
- **Run regularly**: Keep documentation current
- **Review changes**: Always review auto-generated updates
- **Preserve custom**: Keep manual additions safe
- **Commit with code**: Update docs alongside code changes
- **Be specific**: Use specific doc names for targeted updates
- **Bulk updates**: Use category updates for efficiency
- **Verify diagrams**: Check generated diagrams for accuracy
---
**Template Location**: `commands/docs/templates/`
**Output Directory**: `docs/`
**Safe Mode**: Always preserves custom content