feat: upgrade all 12 skills to Vercel structure

Comprehensive upgrade following vercel-labs/agent-skills structure:

## Changes Per Skill

All 12 skills now include:
-  YAML frontmatter on all 307 rule files (title, impact, tags)
-  _sections.md - Category definitions with impact levels
-  _template.md - Standardized template for new rules
-  metadata.json - Version, references, and structured metadata
-  Updated SKILL.md - Added license and metadata frontmatter
-  AGENTS.md - Comprehensive compiled documentation for AI agents

## New Files Created (48 total)

**AGENTS.md** (12 files):
- react-vite-best-practices: 4,751 lines
- typescript-react-patterns: 14KB
- laravel-best-practices: 155KB
- laravel-inertia-react: Full stack integration guide
- tailwind-best-practices: Tailwind v4.0+ patterns
- state-management: 14KB React Query + Zustand
- web-design-guidelines: WCAG 2.2 compliant
- php-best-practices: 779 lines PHP 8.5+
- clean-code-principles: Language-agnostic SOLID/DRY
- api-design-patterns: 144KB REST/OpenAPI
- git-workflow: 26 rules with 12 authoritative references
- testing-best-practices: Jest/Vitest/Testing Library

**metadata.json** (12 files):
- Official documentation references
- Version and organization info
- Rule statistics and categories

**_sections.md** (12 files):
- Category definitions (5-8 per skill)
- Impact levels (CRITICAL/HIGH/MEDIUM/LOW)
- Detailed descriptions

**_template.md** (12 files):
- Standardized rule creation templates
- Consistent formatting guidelines

## Statistics

- 365 files changed
- 31,237 insertions
- 307 rule files with YAML frontmatter
- 12 comprehensive AGENTS.md documents
- Focus areas: React+Vite, TypeScript, Laravel 12, PHP 8.5, Tailwind v4

## References

Following structure from vercel-labs/agent-skills while customizing
for our stack: React, Vite, TypeScript, Laravel 12, Inertia.js,
Tailwind CSS v4, PHP 8.5, React Query, Zustand, WCAG 2.2

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Asyraf Hussin
2026-01-17 06:34:49 +08:00
parent d42d899fc1
commit 86e1203039
365 changed files with 31226 additions and 412 deletions
+1
View File
@@ -3,3 +3,4 @@
node_modules/
.env
.env.local
vercel-agent-skills/
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1,6 +1,10 @@
---
name: api-design-patterns
description: RESTful API design, error handling, versioning, and best practices. Use when designing APIs, reviewing endpoints, implementing error responses, or setting up API structure. Triggers on "design API", "review API", "REST best practices", or "API patterns".
license: MIT
metadata:
author: api-design-patterns
version: "1.0.0"
---
# API Design Patterns
@@ -0,0 +1,124 @@
# API Design Patterns Skill - Upgrade Summary
## Completed Upgrades
This skill has been upgraded to follow Vercel's structure with all 6 required tasks completed:
### ✅ 1. YAML Frontmatter Added to All Rule Files (21 rules)
All rule files now have consistent YAML frontmatter with:
- `title`: Descriptive title of the rule
- `impact`: CRITICAL, HIGH, or MEDIUM
- `impactDescription`: Brief description of the impact
- `tags`: Relevant tags for categorization
**Example:**
```yaml
---
title: Use Nouns, Not Verbs for Resource Names
impact: CRITICAL
impactDescription: Foundation of REST architecture
tags: rest, resources, naming, http-methods
---
```
**Rules Updated:**
- **REST (8 rules):** rest-nouns-not-verbs, rest-plural-resources, rest-http-methods, rest-nested-resources, rest-status-codes, rest-idempotency, rest-hateoas, rest-resource-actions
- **Error Handling (6 rules):** error-consistent-format, error-meaningful-messages, error-error-codes, error-validation-details, error-no-stack-traces, error-request-id
- **Security (7 rules):** sec-authentication, sec-authorization, sec-cors-config, sec-https-only, sec-input-validation, sec-rate-limiting, sec-sensitive-data
### ✅ 2. Created _sections.md
Defines 7 categories with impact levels and descriptions:
1. **Resource Design (rest)** - CRITICAL
2. **Error Handling (error)** - CRITICAL
3. **Security (sec)** - CRITICAL
4. **Pagination & Filtering (page)** - HIGH
5. **Versioning (ver)** - HIGH
6. **Response Format (resp)** - MEDIUM
7. **Documentation (doc)** - MEDIUM
### ✅ 3. Created _template.md
Template for creating new rule files with:
- YAML frontmatter structure
- Rule explanation format
- Incorrect/Correct example sections
- "Why" benefits section
- Reference links
### ✅ 4. Created metadata.json
Contains:
- Version: 1.0.0
- Organization: API Design Patterns
- Date: January 2026
- Abstract: Comprehensive description of the skill
- **References:**
- https://restfulapi.net
- https://zalando.github.io/restful-api-guidelines
- RFC 7231 (HTTP/1.1 Semantics)
- RFC 6749 (OAuth 2.0)
- https://jwt.io
- OpenAPI/Swagger specification
- Microsoft API Guidelines
- Google APIs Explorer
### ✅ 5. Updated SKILL.md with License/Metadata
Added to frontmatter:
```yaml
license: MIT
metadata:
author: api-design-patterns
version: "1.0.0"
```
### ✅ 6. Generated AGENTS.md
Comprehensive compiled documentation (5,658 lines) containing:
- Complete skill overview
- All 7 section descriptions
- All 21 detailed rule implementations
- RESTful API examples (Node.js, Python, JSON)
- Error handling patterns
- Security best practices
- References and links
## File Structure
```
api-design-patterns/
├── AGENTS.md # Complete compiled documentation (144KB)
├── SKILL.md # Skill definition with frontmatter
├── README.md # Original README
├── metadata.json # Metadata and references
├── UPGRADE_SUMMARY.md # This file
└── rules/
├── _sections.md # Section definitions
├── _template.md # Rule template
├── rest-*.md # 8 REST resource design rules
├── error-*.md # 6 error handling rules
└── sec-*.md # 7 security rules
```
## Key Features
1. **Focus on RESTful API Design**: Covers resource naming, HTTP methods, status codes, idempotency
2. **Comprehensive Error Handling**: Consistent formats, meaningful messages, validation details
3. **Security-First**: Authentication, authorization, HTTPS, input validation, rate limiting
4. **Good API Examples**: Real-world code in Node.js/Express, Python/FastAPI, JSON
5. **Industry References**: Links to RESTful API best practices, Zalando guidelines, RFCs
## Usage
For AI agents and developers:
- Reference SKILL.md for quick guidelines and examples
- Use individual rule files (rules/*.md) for detailed implementations
- Consult AGENTS.md for complete reference documentation
- Follow _template.md when creating new rules
---
**Upgrade Date:** January 17, 2026
**Structure Based On:** Vercel Agent Skills Format
+21
View File
@@ -0,0 +1,21 @@
{
"version": "1.0.0",
"organization": "API Design Patterns",
"date": "January 2026",
"abstract": "Comprehensive RESTful API design guidelines covering resource naming, HTTP methods, error handling, pagination, versioning, and security best practices. Contains 21 rules across 7 categories, prioritized by impact from critical (REST fundamentals, error handling, security) to medium (documentation). Each rule includes detailed explanations with real-world examples comparing incorrect vs. correct implementations, designed for AI agents and developers building production-ready APIs.",
"references": [
"https://restfulapi.net",
"https://restfulapi.net/http-methods",
"https://restfulapi.net/http-status-codes",
"https://restfulapi.net/resource-naming",
"https://restfulapi.net/idempotent-rest-apis",
"https://restfulapi.net/hateoas",
"https://zalando.github.io/restful-api-guidelines",
"https://www.ietf.org/rfc/rfc7231.txt",
"https://www.ietf.org/rfc/rfc6749.txt",
"https://jwt.io",
"https://swagger.io/specification",
"https://github.com/microsoft/api-guidelines",
"https://developers.google.com/apis-explorer"
]
}
@@ -0,0 +1,41 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Resource Design (rest)
**Impact:** CRITICAL
**Description:** REST resource design is the foundation of a well-architected API. Proper HTTP method usage, status codes, and resource naming enable caching, retry logic, and semantic operations. Idempotency prevents duplicate operations.
## 2. Error Handling (error)
**Impact:** CRITICAL
**Description:** Consistent, detailed error responses reduce support burden and enable programmatic error handling. Machine-readable error codes, validation details, and request IDs are essential for debugging and monitoring.
## 3. Security (sec)
**Impact:** CRITICAL
**Description:** Security controls protect user data and prevent abuse. Authentication, authorization, HTTPS, input validation, rate limiting, and sensitive data protection are non-negotiable for production APIs.
## 4. Pagination & Filtering (page)
**Impact:** HIGH
**Description:** Efficient data retrieval for large datasets. Cursor and offset-based pagination, consistent parameter naming, and flexible filtering reduce API response times and improve user experience.
## 5. Versioning (ver)
**Impact:** HIGH
**Description:** API versioning enables evolution without breaking existing clients. URL path or header-based versioning, backward compatibility, and deprecation strategies manage API changes gracefully.
## 6. Response Format (resp)
**Impact:** MEDIUM
**Description:** Consistent response structure, JSON conventions, and field selection improve API predictability and developer experience. Response compression reduces bandwidth usage.
## 7. Documentation (doc)
**Impact:** MEDIUM
**Description:** OpenAPI/Swagger specs, request/response examples, and changelogs make APIs self-documenting and reduce integration time for developers.
@@ -0,0 +1,45 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact
tags: tag1, tag2, tag3
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters for API design. Focus on the benefits and problems it solves.
**Incorrect (description of what's wrong):**
```json
// Bad example showing the anti-pattern
{
"example": "bad"
}
```
**Correct (description of what's right):**
```json
// Good example showing the recommended pattern
{
"example": "good"
}
```
```javascript
// Additional code examples if needed
app.get('/endpoint', (req, res) => {
// Implementation
});
```
## Why
1. **Benefit 1**: Explanation of why this matters
2. **Benefit 2**: Another important reason
3. **Benefit 3**: Additional context
Reference: [Link to documentation](https://example.com)
@@ -1,9 +1,13 @@
# error-consistent-format
---
title: Consistent Error Response Format
impact: CRITICAL
impactDescription: Enables predictable error handling across API
tags: errors, consistency, response-format, client-experience
---
**Priority:** CRITICAL
**Category:** Error Handling
## Consistent Error Response Format
## Why It Matters
**Impact: CRITICAL**
Inconsistent error formats force API consumers to handle multiple error structures, leading to fragile client code. A consistent error format makes APIs predictable, easier to debug, and simpler to integrate. Clients can build reusable error handling logic.
@@ -1,4 +1,11 @@
# Use Machine-Readable Error Codes
---
title: Use Machine-Readable Error Codes
impact: HIGH
impactDescription: Enables programmatic error handling and client recovery
tags: errors, error-codes, automation, monitoring
---
## Use Machine-Readable Error Codes
Include standardized, machine-readable error codes alongside human-readable messages to enable programmatic error handling.
@@ -1,4 +1,11 @@
# Provide Meaningful Error Messages
---
title: Provide Meaningful Error Messages
impact: HIGH
impactDescription: Reduces support burden and improves developer experience
tags: errors, messages, user-experience, actionable
---
## Provide Meaningful Error Messages
Error messages should be clear, actionable, and help users understand what went wrong and how to fix it.
@@ -1,4 +1,11 @@
# Never Expose Stack Traces in Production
---
title: Never Expose Stack Traces in Production
impact: CRITICAL
impactDescription: Prevents security vulnerabilities and information disclosure
tags: errors, security, production, sensitive-data
---
## Never Expose Stack Traces in Production
Stack traces and internal error details should never be exposed to API clients in production environments, as they reveal implementation details and potential vulnerabilities.
@@ -1,4 +1,11 @@
# Include Request ID in Error Responses
---
title: Include Request ID in Error Responses
impact: HIGH
impactDescription: Enables log correlation and efficient debugging
tags: errors, debugging, logging, request-tracking
---
## Include Request ID in Error Responses
Every API request should have a unique identifier that appears in both the response and server logs, enabling easy correlation for debugging.
@@ -1,4 +1,11 @@
# Include Validation Error Details
---
title: Include Validation Error Details
impact: HIGH
impactDescription: Enables field-level error feedback for better UX
tags: errors, validation, form-handling, user-experience
---
## Include Validation Error Details
When validation fails, provide specific details about which fields failed and why, enabling clients to display targeted error messages.
@@ -1,4 +1,11 @@
# Include HATEOAS Links for Discoverability
---
title: Include HATEOAS Links for Discoverability
impact: MEDIUM
impactDescription: Improves API discoverability and reduces client coupling
tags: rest, hateoas, hypermedia, discoverability
---
## Include HATEOAS Links for Discoverability
HATEOAS (Hypermedia as the Engine of Application State) provides links in responses that guide clients to related resources and available actions.
@@ -1,4 +1,11 @@
# Use HTTP Methods Correctly
---
title: Use HTTP Methods Correctly
impact: CRITICAL
impactDescription: Enables caching, retry logic, and semantic API operations
tags: rest, http-methods, idempotency, safety
---
## Use HTTP Methods Correctly
HTTP methods have specific semantics and should be used according to their intended purpose. Each method has distinct characteristics for safety and idempotency.
@@ -1,4 +1,11 @@
# Implement Idempotency for Safe Retries
---
title: Implement Idempotency for Safe Retries
impact: CRITICAL
impactDescription: Prevents duplicate operations and enables safe retries
tags: rest, idempotency, reliability, retries
---
## Implement Idempotency for Safe Retries
Idempotent operations produce the same result regardless of how many times they're executed. Implement idempotency keys for non-idempotent operations to enable safe retries.
@@ -1,4 +1,11 @@
# Design Nested Resources for Hierarchical Relationships
---
title: Design Nested Resources for Hierarchical Relationships
impact: HIGH
impactDescription: Clarifies resource relationships and authorization boundaries
tags: rest, resources, nesting, hierarchy
---
## Design Nested Resources for Hierarchical Relationships
Use nested URLs to represent parent-child relationships between resources, but avoid deep nesting beyond two levels.
@@ -1,4 +1,11 @@
# Use Nouns, Not Verbs for Resource Names
---
title: Use Nouns, Not Verbs for Resource Names
impact: CRITICAL
impactDescription: Foundation of REST architecture
tags: rest, resources, naming, http-methods
---
## Use Nouns, Not Verbs for Resource Names
REST API endpoints should represent resources (nouns), not actions (verbs). HTTP methods already convey the action being performed.
@@ -1,4 +1,11 @@
# Use Plural Nouns for Resource Collections
---
title: Use Plural Nouns for Resource Collections
impact: HIGH
impactDescription: Improves API consistency and predictability
tags: rest, resources, naming, conventions
---
## Use Plural Nouns for Resource Collections
Resource names should consistently use plural nouns to represent collections, maintaining uniformity across your API.
@@ -1,4 +1,11 @@
# Handle Non-CRUD Actions on Resources
---
title: Handle Non-CRUD Actions on Resources
impact: HIGH
impactDescription: Proper handling of complex operations and state transitions
tags: rest, actions, state-transitions, workflows
---
## Handle Non-CRUD Actions on Resources
Some operations don't fit standard CRUD patterns. Use sub-resources or action endpoints for operations that represent state transitions or complex actions.
@@ -1,4 +1,11 @@
# Use Appropriate HTTP Status Codes
---
title: Use Appropriate HTTP Status Codes
impact: CRITICAL
impactDescription: Enables proper client handling, caching, and monitoring
tags: rest, http-status, errors, semantics
---
## Use Appropriate HTTP Status Codes
Return semantically correct HTTP status codes that accurately describe the result of the operation.
@@ -1,4 +1,11 @@
# Implement Secure Authentication
---
title: Implement Secure Authentication
impact: CRITICAL
impactDescription: Protects user data and prevents unauthorized access
tags: security, authentication, jwt, oauth2, tokens
---
## Implement Secure Authentication
Use industry-standard authentication mechanisms like OAuth 2.0, JWT, or API keys with proper security practices.
@@ -1,4 +1,11 @@
# Implement Proper Authorization
---
title: Implement Proper Authorization
impact: CRITICAL
impactDescription: Enforces access control and resource permissions
tags: security, authorization, rbac, permissions, access-control
---
## Implement Proper Authorization
Authorization verifies what authenticated users can do. Implement role-based (RBAC) or attribute-based (ABAC) access control consistently.
@@ -1,4 +1,11 @@
# Configure CORS Properly
---
title: Configure CORS Properly
impact: HIGH
impactDescription: Prevents unauthorized cross-origin access
tags: security, cors, cross-origin, browsers
---
## Configure CORS Properly
Cross-Origin Resource Sharing (CORS) must be configured correctly to allow legitimate cross-origin requests while preventing unauthorized access.
@@ -1,4 +1,11 @@
# Enforce HTTPS Only
---
title: Enforce HTTPS Only
impact: CRITICAL
impactDescription: Protects data in transit from interception
tags: security, https, encryption, tls
---
## Enforce HTTPS Only
All API traffic must use HTTPS to encrypt data in transit. Never allow unencrypted HTTP connections for APIs.
@@ -1,4 +1,11 @@
# Validate All Input Data
---
title: Validate All Input Data
impact: CRITICAL
impactDescription: Prevents injection attacks and malformed data
tags: security, validation, input-sanitization, injection
---
## Validate All Input Data
Never trust client input. Validate, sanitize, and constrain all incoming data to prevent security vulnerabilities.
@@ -1,4 +1,11 @@
# Implement Rate Limiting
---
title: Implement Rate Limiting
impact: CRITICAL
impactDescription: Prevents abuse and ensures service availability
tags: security, rate-limiting, abuse-prevention, throttling
---
## Implement Rate Limiting
Protect your API from abuse by limiting the number of requests clients can make within a time window.
@@ -1,4 +1,11 @@
# Protect Sensitive Data in Responses
---
title: Protect Sensitive Data in Responses
impact: CRITICAL
impactDescription: Prevents data leaks and privacy violations
tags: security, privacy, sensitive-data, pii
---
## Protect Sensitive Data in Responses
Never expose sensitive information like passwords, tokens, internal IDs, or PII in API responses.
+443
View File
@@ -0,0 +1,443 @@
# Clean Code Principles - Agent Documentation
This skill provides comprehensive clean code principles, SOLID guidelines, and design patterns for building maintainable, scalable software.
## Overview
The clean-code-principles skill offers language-agnostic software design principles organized into 7 categories, from CRITICAL (SOLID, Core Principles) to LOW priority (Comments). Each rule provides bad/good examples, explanations, and practical guidance.
## When to Use This Skill
Activate this skill when:
- Reviewing code architecture or design
- Refactoring existing code
- Making design decisions
- Establishing coding standards
- Teaching software design principles
- Addressing technical debt
- Improving code quality and maintainability
## Trigger Phrases
The skill activates on:
- "review architecture"
- "check code quality"
- "SOLID principles"
- "design patterns"
- "clean code"
- "refactoring advice"
- "code smells"
- "best practices"
- "DRY principle"
- "separation of concerns"
## Skill Structure
```
clean-code-principles/
├── SKILL.md # Main skill definition
├── AGENTS.md # This file - agent documentation
├── README.md # User-facing documentation
├── metadata.json # Structured metadata and references
└── rules/
├── _sections.md # Category definitions and organization
├── _template.md # Template for new rules
├── solid-*.md # SOLID principles (10 rules)
├── core-*.md # Core principles (12 rules)
└── pattern-*.md # Design patterns (1 rule)
```
## Rule Categories
### 1. SOLID Principles (CRITICAL - 10 rules)
**Prefix:** `solid-`
Five fundamental object-oriented design principles:
- **S**ingle Responsibility: `solid-srp-class`, `solid-srp-function`
- **O**pen/Closed: `solid-ocp-extension`, `solid-ocp-abstraction`
- **L**iskov Substitution: `solid-lsp-contracts`, `solid-lsp-preconditions`
- **I**nterface Segregation: `solid-isp-clients`, `solid-isp-interfaces`
- **D**ependency Inversion: `solid-dip-abstractions`, `solid-dip-injection`
**Use when:** Designing architecture, planning refactoring, discussing system design
### 2. Core Principles (CRITICAL - 12 rules)
**Prefix:** `core-`
Fundamental coding practices:
- **DRY** (Don't Repeat Yourself): 3 rules
- **KISS** (Keep It Simple): 2 rules
- **YAGNI** (You Aren't Gonna Need It): 2 rules
- **Other**: Separation of Concerns, Composition Over Inheritance, Law of Demeter, Fail Fast, Encapsulation
**Use when:** Daily coding, code reviews, addressing duplication or complexity
### 3. Design Patterns (HIGH - 1 rule)
**Prefix:** `pattern-`
Common solutions to recurring problems:
- Repository Pattern (data access abstraction)
**Use when:** Solving architectural problems, abstracting infrastructure concerns
### 4-7. Future Categories
- **Code Organization** (`org-`): Module structure, boundaries
- **Naming & Readability** (`name-`): Identifier naming conventions
- **Functions & Methods** (`func-`): Function-level best practices
- **Comments & Documentation** (`doc-`): Documentation guidelines
## How to Use Rules
### Accessing Rules
1. **By ID:** Reference specific rules using their ID
```
Check against solid-srp-class and core-dry
```
2. **By Category:** Apply all rules in a category
```
Review this class against SOLID principles
```
3. **By Scenario:** Choose relevant rules for the context
```
This has duplicated validation logic - check DRY rules
```
### Rule Format
Each rule follows a consistent structure:
```markdown
---
id: {rule-id}
title: {Full Title}
category: {category}
priority: {critical|high|medium|low}
tags: [{tags}]
related: [{related-rule-ids}]
---
# {Rule Title}
{One-sentence summary}
## Bad Example
{Anti-pattern code with problems listed}
## Good Example
{Correct implementation with benefits}
## Why
{5-7 benefits explaining the value}
## When to Apply
{Practical scenarios}
```
### Output Format
When identifying violations, use:
```
file:line - [rule-id] Description of issue
```
Example:
```
src/services/UserService.ts:15 - [solid-srp-class] Class handles validation, persistence, and notifications
src/utils/helpers.ts:42 - [core-dry] Email validation duplicated from validators/email.ts
src/models/Order.ts:28 - [core-kiss-simplicity] Overly complex abstraction for simple use case
```
## Agent Strategies
### Strategy 1: Architecture Review
**Goal:** Assess overall system design
**Approach:**
1. Start with SOLID principles (highest impact)
2. Identify violations of SRP, DIP, OCP
3. Check for proper separation of concerns
4. Evaluate composition vs inheritance
5. Assess interface design (ISP)
**Output:** Prioritized list of architectural issues with rule references
### Strategy 2: Code Quality Audit
**Goal:** Find code quality issues in specific files
**Approach:**
1. Scan for duplication (DRY rules)
2. Check complexity (KISS rules)
3. Look for overengineering (YAGNI rules)
4. Verify single responsibility
5. Assess encapsulation
**Output:** File-by-file findings with specific line references
### Strategy 3: Refactoring Guidance
**Goal:** Provide actionable refactoring steps
**Approach:**
1. Identify the primary issue (which rule violated)
2. Reference the good example from that rule
3. Suggest specific refactoring steps
4. Mention related rules that may also help
5. Prioritize changes by impact
**Output:** Step-by-step refactoring plan with rule references
### Strategy 4: Design Decision Support
**Goal:** Help choose between design alternatives
**Approach:**
1. Analyze each option against relevant principles
2. Consider YAGNI (simplest solution first)
3. Evaluate against SOLID principles
4. Check alignment with KISS
5. Recommend based on principle adherence
**Output:** Comparative analysis with principle-based recommendation
### Strategy 5: Pattern Application
**Goal:** Suggest appropriate design patterns
**Approach:**
1. Identify the problem being solved
2. Check if any patterns apply
3. Verify pattern aligns with SOLID principles
4. Ensure pattern isn't overengineering (YAGNI)
5. Provide implementation guidance
**Output:** Pattern recommendation with integration guidance
## Best Practices for Agents
### Do:
- Start with CRITICAL rules (SOLID, Core)
- Provide specific line numbers when possible
- Reference rule IDs in all findings
- Explain WHY a rule matters, not just that it's violated
- Give actionable refactoring suggestions
- Consider the codebase context
- Prioritize by impact (CRITICAL > HIGH > MEDIUM > LOW)
- Show code examples from the rules
- Mention related rules that apply together
### Don't:
- Don't cite every minor violation
- Don't recommend patterns without clear need (YAGNI)
- Don't ignore context (some violations may be acceptable)
- Don't focus on LOW priority rules when CRITICAL issues exist
- Don't provide fixes without explaining the principle
- Don't recommend complex solutions for simple problems (KISS)
- Don't suggest abstractions without concrete use cases (YAGNI)
### Prioritization
When multiple issues exist:
1. **CRITICAL - SOLID violations:** Architecture-level problems
2. **CRITICAL - Core violations:** Duplication, complexity, overengineering
3. **HIGH - Pattern opportunities:** Where patterns genuinely help
4. **MEDIUM - Naming/Functions:** Readability improvements
5. **LOW - Documentation:** Comment and doc issues
## Example Interactions
### Example 1: Architecture Review
**User:** "Review the architecture of this OrderService class"
**Agent Approach:**
1. Check class responsibilities against `solid-srp-class`
2. Evaluate dependencies against `solid-dip-injection`
3. Look for data access against `pattern-repository`
4. Check for proper separation against `core-separation-concerns`
**Agent Output:**
```
Architecture Review - OrderService
CRITICAL Issues:
1. [solid-srp-class] Class has multiple responsibilities:
- Order validation (should be separate validator)
- Direct database access (should use repository)
- Email sending (should be separate service)
- Payment processing (should be separate service)
2. [solid-dip-abstractions] Direct dependency on concrete implementations:
- Instantiates MySQLDatabase directly (line 15)
- Creates StripePaymentGateway in constructor (line 18)
3. [pattern-repository] Direct SQL queries in service layer:
- Lines 45-50: Raw SQL should be in repository
Recommendations:
1. Split into focused classes following SRP
2. Inject dependencies through constructor (DIP)
3. Create repository abstraction for data access
4. Extract email and payment to separate services
See: solid-srp-class.md, solid-dip-injection.md, pattern-repository.md
```
### Example 2: Code Quality Check
**User:** "Check this validation function for code quality issues"
**Agent Approach:**
1. Check for duplication (`core-dry`)
2. Check complexity (`core-kiss-simplicity`)
3. Check function responsibility (`solid-srp-function`)
**Agent Output:**
```
Code Quality Issues:
utils/validation.ts:
Line 23 - [core-dry] Email regex duplicated from line 45 and validators/email.ts
Line 30 - [core-dry-extraction] Password validation logic should be extracted to reusable function
Line 50 - [solid-srp-function] Function validates both email AND password - split into two functions
Suggested refactoring:
1. Extract common regex patterns to constants file (core-dry-single-source)
2. Create separate validateEmail() and validatePassword() functions (solid-srp-function)
3. Import from shared validators module (core-dry-extraction)
See: core-dry.md, core-dry-extraction.md, solid-srp-function.md
```
### Example 3: Design Decision
**User:** "Should I use inheritance or composition for this User/Admin relationship?"
**Agent Approach:**
1. Apply `core-composition` principle
2. Check LSP implications (`solid-lsp-contracts`)
3. Consider YAGNI (`core-yagni-abstractions`)
**Agent Output:**
```
Recommendation: Use Composition
Analysis:
1. [core-composition] Composition is preferred over inheritance for flexibility
- Admins can have additional capabilities without inheritance constraints
- Easier to test each capability independently
- Can mix different permission sets dynamically
2. [solid-lsp-contracts] Inheritance risks LSP violations
- If Admin overrides User methods differently
- If Admin has different behavior expectations
3. [core-yagni-abstractions] Start simple
- Don't create inheritance hierarchy unless you need polymorphism
- Compose from Permission and Role objects instead
Suggested approach:
```typescript
class User {
constructor(
private permissions: PermissionSet,
private roleManager: RoleManager
) {}
}
```
See: core-composition.md, solid-lsp-contracts.md
```
## Integration with Other Skills
This skill complements:
- **refactoring**: Provides principles for refactoring decisions
- **architecture-review**: Supplies SOLID and design principles
- **code-review**: Offers quality criteria for reviews
- **testing**: Promotes testable design (DIP, SRP)
## Rule Reference Quick Guide
### Most Common Rules
**For duplication:**
- `core-dry` - Main DRY principle
- `core-dry-extraction` - How to extract duplicated code
- `core-dry-single-source` - Configuration and constants
**For complex code:**
- `core-kiss-simplicity` - Avoid overengineering
- `core-kiss-readability` - Optimize for readability
- `core-yagni-features` - Don't build unused features
- `core-yagni-abstractions` - Don't abstract prematurely
**For class design:**
- `solid-srp-class` - Single responsibility for classes
- `solid-dip-injection` - Dependency injection
- `core-separation-concerns` - Separate different concerns
- `core-composition` - Favor composition over inheritance
**For function design:**
- `solid-srp-function` - Single responsibility for functions
- `core-kiss-readability` - Clear, readable functions
**For interfaces:**
- `solid-isp-interfaces` - Small, focused interfaces
- `solid-isp-clients` - Client-specific interfaces
**For extensibility:**
- `solid-ocp-extension` - Open for extension, closed for modification
- `solid-ocp-abstraction` - Use abstractions for extension points
**For inheritance:**
- `solid-lsp-contracts` - Subtypes must honor contracts
- `solid-lsp-preconditions` - Pre/postcondition rules
- `core-composition` - Prefer composition
**For data access:**
- `pattern-repository` - Abstract data persistence
## Metadata
**Version:** 1.0.0
**Rules:** 23 (10 SOLID, 12 Core, 1 Pattern)
**Categories:** 7 (3 implemented, 4 planned)
**Languages:** Language-agnostic (examples in TypeScript)
**Last Updated:** 2026-01-17
## Resources
### Books
- Clean Code (Robert C. Martin)
- Design Patterns (Gang of Four)
- Refactoring (Martin Fowler)
- The Pragmatic Programmer (Hunt & Thomas)
### Online
- [Refactoring Guru](https://refactoring.guru/) - Design patterns and code smells
- [Martin Fowler's Catalog](https://refactoring.com/catalog/) - Refactoring techniques
- [Uncle Bob's Blog](https://blog.cleancoder.com/) - Software craftsmanship
## Contributing New Rules
When adding new rules:
1. Use `rules/_template.md` as starting point
2. Follow naming convention: `{prefix}-{concept}-{specificity}.md`
3. Include YAML frontmatter with all required fields
4. Provide clear bad/good examples
5. Explain 5-7 benefits in "Why" section
6. Add to `metadata.json` rules array
7. Update category counts in `_sections.md`
8. Reference related rules in frontmatter
9. Keep examples language-agnostic (TypeScript preferred)
10. Aim for 300-400 lines of content
## License
MIT License - See SKILL.md for full license text
+56 -1
View File
@@ -171,7 +171,62 @@ src/models/Order.ts:28 - [name-meaningful] Variable 'x' should describe its purp
Read individual rule files for detailed explanations:
```
rules/solid-srp.md
rules/solid-srp-class.md
rules/core-dry.md
rules/pattern-repository.md
```
## References
This skill is built on established software engineering principles:
### Core Books
- **Clean Code** by Robert C. Martin - Foundation for clean code practices
- **Design Patterns** by Gang of Four - Classic design pattern catalog
- **Refactoring** by Martin Fowler - Improving code structure
- **The Pragmatic Programmer** by Hunt & Thomas - Practical wisdom
### Online Resources
- [Refactoring Guru](https://refactoring.guru/) - Design patterns and code smells
- [Martin Fowler's Refactoring Catalog](https://refactoring.com/catalog/) - Comprehensive refactoring techniques
- [Uncle Bob's Clean Coder Blog](https://blog.cleancoder.com/) - Software craftsmanship articles
### Pattern Catalogs
- [Refactoring Guru - Design Patterns](https://refactoring.guru/design-patterns)
- [Martin Fowler - Enterprise Patterns](https://martinfowler.com/eaaCatalog/)
## Metadata
**Version:** 1.0.0
**Status:** Active
**Coverage:** 23 rules across 3 categories (SOLID, Core Principles, Design Patterns)
**Last Updated:** 2026-01-17
### Rule Statistics
- SOLID Principles: 10 rules
- Core Principles: 12 rules
- Design Patterns: 1 rule
## License
MIT License
Copyright (c) 2026 Agent Skills
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+374
View File
@@ -0,0 +1,374 @@
{
"name": "clean-code-principles",
"version": "1.0.0",
"description": "SOLID principles, design patterns, DRY, KISS, and clean code fundamentals for writing maintainable, scalable software",
"author": "Agent Skills",
"license": "MIT",
"tags": [
"SOLID",
"clean-code",
"design-patterns",
"DRY",
"KISS",
"YAGNI",
"best-practices",
"software-architecture",
"code-quality",
"refactoring"
],
"categories": [
{
"id": "solid-principles",
"name": "SOLID Principles",
"priority": "critical",
"prefix": "solid-",
"count": 10,
"description": "Five fundamental principles of object-oriented design"
},
{
"id": "core-principles",
"name": "Core Principles",
"priority": "critical",
"prefix": "core-",
"count": 12,
"description": "Fundamental coding principles like DRY, KISS, and YAGNI"
},
{
"id": "design-patterns",
"name": "Design Patterns",
"priority": "high",
"prefix": "pattern-",
"count": 1,
"description": "Common design patterns for recurring problems"
},
{
"id": "code-organization",
"name": "Code Organization",
"priority": "high",
"prefix": "org-",
"count": 0,
"description": "Project structure and module boundaries"
},
{
"id": "naming-readability",
"name": "Naming & Readability",
"priority": "medium",
"prefix": "name-",
"count": 0,
"description": "Naming conventions and code readability"
},
{
"id": "functions-methods",
"name": "Functions & Methods",
"priority": "medium",
"prefix": "func-",
"count": 0,
"description": "Function-level best practices"
},
{
"id": "comments-documentation",
"name": "Comments & Documentation",
"priority": "low",
"prefix": "doc-",
"count": 0,
"description": "Documentation and commenting guidelines"
}
],
"rules": [
{
"id": "solid-srp-class",
"title": "SOLID - Single Responsibility Principle (Class Level)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-srp-function",
"title": "SOLID - Single Responsibility Principle (Function Level)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-ocp-extension",
"title": "SOLID - Open/Closed Principle (Extension)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-ocp-abstraction",
"title": "SOLID - Open/Closed (Abstraction)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-lsp-contracts",
"title": "SOLID - Liskov Substitution (Contracts)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-lsp-preconditions",
"title": "SOLID - Liskov Substitution (Preconditions)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-isp-clients",
"title": "SOLID - Interface Segregation (Client-Specific)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-isp-interfaces",
"title": "SOLID - Interface Segregation (Small Interfaces)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-dip-abstractions",
"title": "SOLID - Dependency Inversion (Abstractions)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "solid-dip-injection",
"title": "SOLID - Dependency Inversion (Injection)",
"category": "solid-principles",
"priority": "critical"
},
{
"id": "core-dry",
"title": "Don't Repeat Yourself (DRY)",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-dry-extraction",
"title": "DRY - Code Extraction",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-dry-single-source",
"title": "DRY - Single Source of Truth",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-kiss-simplicity",
"title": "KISS - Simplicity",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-kiss-readability",
"title": "KISS - Readability",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-yagni-features",
"title": "YAGNI - Features",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-yagni-abstractions",
"title": "YAGNI - Abstractions",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-separation-concerns",
"title": "Separation of Concerns",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-composition",
"title": "Composition Over Inheritance",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-law-demeter",
"title": "Law of Demeter",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-fail-fast",
"title": "Fail Fast Principle",
"category": "core-principles",
"priority": "critical"
},
{
"id": "core-encapsulation",
"title": "Encapsulation",
"category": "core-principles",
"priority": "critical"
},
{
"id": "pattern-repository",
"title": "Design Pattern - Repository",
"category": "design-patterns",
"priority": "high"
}
],
"references": {
"books": [
{
"title": "Clean Code: A Handbook of Agile Software Craftsmanship",
"author": "Robert C. Martin",
"year": 2008,
"isbn": "978-0132350884",
"url": "https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"
},
{
"title": "Design Patterns: Elements of Reusable Object-Oriented Software",
"author": "Gang of Four (Gamma, Helm, Johnson, Vlissides)",
"year": 1994,
"isbn": "978-0201633610",
"url": "https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612"
},
{
"title": "Refactoring: Improving the Design of Existing Code",
"author": "Martin Fowler",
"year": 2018,
"isbn": "978-0134757599",
"url": "https://martinfowler.com/books/refactoring.html"
},
{
"title": "The Pragmatic Programmer",
"author": "Andrew Hunt and David Thomas",
"year": 2019,
"isbn": "978-0135957059",
"url": "https://pragprog.com/titles/tpp20/the-pragmatic-programmer-20th-anniversary-edition/"
},
{
"title": "Patterns of Enterprise Application Architecture",
"author": "Martin Fowler",
"year": 2002,
"isbn": "978-0321127426",
"url": "https://martinfowler.com/books/eaa.html"
}
],
"websites": [
{
"title": "Refactoring Guru - Design Patterns",
"url": "https://refactoring.guru/design-patterns",
"description": "Comprehensive catalog of design patterns with examples in multiple languages"
},
{
"title": "Refactoring Guru - Code Smells",
"url": "https://refactoring.guru/refactoring/smells",
"description": "Catalog of code smells and refactoring techniques"
},
{
"title": "Martin Fowler - Refactoring Catalog",
"url": "https://refactoring.com/catalog/",
"description": "Comprehensive refactoring catalog by Martin Fowler"
},
{
"title": "Martin Fowler - Bliki",
"url": "https://martinfowler.com/bliki/",
"description": "Martin Fowler's blog with articles on software design"
},
{
"title": "SOLID Principles",
"url": "https://en.wikipedia.org/wiki/SOLID",
"description": "Wikipedia article on SOLID principles"
},
{
"title": "Robert C. Martin (Uncle Bob) - Blog",
"url": "https://blog.cleancoder.com/",
"description": "Articles on clean code and software craftsmanship"
}
],
"articles": [
{
"title": "The DRY Principle",
"author": "Martin Fowler",
"url": "https://martinfowler.com/ieeeSoftware/repetition.pdf",
"description": "In-depth article on avoiding duplication"
},
{
"title": "SOLID Principles Explained",
"author": "Various",
"url": "https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design",
"description": "Practical explanation of SOLID principles"
},
{
"title": "Composition vs Inheritance",
"author": "Gang of Four",
"url": "https://en.wikipedia.org/wiki/Composition_over_inheritance",
"description": "Discussion of composition over inheritance principle"
}
],
"videos": [
{
"title": "Clean Code - Uncle Bob / Lesson 1",
"url": "https://www.youtube.com/watch?v=7EmboKQH8lM",
"description": "Introduction to clean code principles"
},
{
"title": "SOLID Principles of Object Oriented Design",
"url": "https://www.youtube.com/watch?v=TMuno5RZNeE",
"description": "Conference talk on SOLID principles"
}
]
},
"keywords": [
"software design",
"architecture",
"maintainability",
"scalability",
"testability",
"code quality",
"best practices",
"object-oriented design",
"functional programming",
"design principles",
"code organization",
"refactoring",
"technical debt",
"clean architecture"
],
"languages": [
"typescript",
"javascript",
"python",
"java",
"go",
"rust",
"c-sharp",
"php",
"ruby"
],
"compatibility": {
"paradigms": [
"object-oriented",
"functional",
"procedural",
"declarative"
],
"scales": [
"single-file",
"module",
"application",
"microservices",
"distributed-systems"
]
},
"metadata": {
"created": "2026-01-17",
"updated": "2026-01-17",
"status": "active",
"maturity": "stable",
"coverage": {
"total_categories": 7,
"implemented_categories": 3,
"total_rules": 23,
"coverage_percentage": 42.86
}
}
}
@@ -0,0 +1,320 @@
# Clean Code Principles - Rule Categories
This document defines the organizational structure for clean code principles, ordered by priority and impact.
## Category Overview
| Priority | Category | Impact | Rule Count | Prefix |
|----------|----------|--------|------------|--------|
| 1 | SOLID Principles | CRITICAL | 10 | `solid-` |
| 2 | Core Principles | CRITICAL | 12 | `core-` |
| 3 | Design Patterns | HIGH | 1 | `pattern-` |
| 4 | Code Organization | HIGH | 0 | `org-` |
| 5 | Naming & Readability | MEDIUM | 0 | `name-` |
| 6 | Functions & Methods | MEDIUM | 0 | `func-` |
| 7 | Comments & Documentation | LOW | 0 | `doc-` |
## 1. SOLID Principles (CRITICAL)
**Priority:** CRITICAL
**Impact:** Architectural foundation, affects entire codebase structure
**Prefix:** `solid-`
The five fundamental principles of object-oriented design that guide maintainable, scalable software architecture.
### Rules
#### Single Responsibility Principle (SRP)
- `solid-srp-class` - A class should have only one reason to change
- `solid-srp-function` - A function should do one thing and do it well
#### Open/Closed Principle (OCP)
- `solid-ocp-extension` - Open for extension, closed for modification
- `solid-ocp-abstraction` - Use abstractions to enable extension
#### Liskov Substitution Principle (LSP)
- `solid-lsp-contracts` - Subtypes must honor base type contracts
- `solid-lsp-preconditions` - Cannot strengthen preconditions or weaken postconditions
#### Interface Segregation Principle (ISP)
- `solid-isp-clients` - Client-specific interfaces, not general-purpose
- `solid-isp-interfaces` - Small, cohesive interfaces
#### Dependency Inversion Principle (DIP)
- `solid-dip-abstractions` - Depend on abstractions, not concretions
- `solid-dip-injection` - Inject dependencies from outside
**Key Concepts:**
- Architectural soundness
- Maintainability at scale
- Testability through design
- Flexibility for change
- Reduced coupling
**When to Apply:**
- Designing new features or systems
- Refactoring existing architecture
- Addressing technical debt
- Improving testability
- Planning for future extensibility
---
## 2. Core Principles (CRITICAL)
**Priority:** CRITICAL
**Impact:** Daily coding practices, code quality foundation
**Prefix:** `core-`
Fundamental principles that apply to every line of code you write, regardless of paradigm or language.
### Rules
#### DRY (Don't Repeat Yourself)
- `core-dry` - Every piece of knowledge should have a single representation
- `core-dry-extraction` - Extract duplicated code into reusable functions
- `core-dry-single-source` - Single source of truth for configuration and data
#### KISS (Keep It Simple, Stupid)
- `core-kiss-simplicity` - Choose the simplest solution that works
- `core-kiss-readability` - Optimize for readability over cleverness
#### YAGNI (You Aren't Gonna Need It)
- `core-yagni-features` - Don't implement features before they're needed
- `core-yagni-abstractions` - Don't create abstractions prematurely
#### Other Core Principles
- `core-separation-concerns` - Different concerns in different modules
- `core-composition` - Favor composition over inheritance
- `core-law-demeter` - Only talk to immediate friends
- `core-fail-fast` - Detect and report errors early
- `core-encapsulation` - Hide implementation details
**Key Concepts:**
- Code duplication elimination
- Simplicity over complexity
- Lean development
- Modularity
- Information hiding
**When to Apply:**
- Writing any new code
- Code reviews
- Refactoring sessions
- Bug fixes
- Performance optimization
---
## 3. Design Patterns (HIGH)
**Priority:** HIGH
**Impact:** Solves recurring problems with proven solutions
**Prefix:** `pattern-`
Common design patterns that provide tested solutions to recurring software design problems.
### Rules
- `pattern-repository` - Abstraction for data access layer
- `pattern-factory` - Object creation without specifying exact class (planned)
- `pattern-strategy` - Encapsulate algorithms for runtime selection (planned)
- `pattern-decorator` - Add behavior without modifying objects (planned)
- `pattern-observer` - Define one-to-many dependencies (planned)
- `pattern-adapter` - Make incompatible interfaces work together (planned)
- `pattern-facade` - Simplified interface to complex subsystems (planned)
**Key Concepts:**
- Proven solutions
- Common vocabulary
- Design reusability
- Best practices codified
- Language-agnostic approaches
**When to Apply:**
- Solving common architectural problems
- Improving code structure
- Reducing coupling between components
- Making systems more testable
- Communicating design intent
---
## 4. Code Organization (HIGH)
**Priority:** HIGH
**Impact:** Project structure, module boundaries, discoverability
**Prefix:** `org-`
Principles for organizing code into modules, packages, and directories for maintainability and scalability.
### Rules (Planned)
- `org-feature-folders` - Organize by feature, not by layer
- `org-module-boundaries` - Clear boundaries between modules
- `org-layered-architecture` - Proper separation of layers
- `org-package-cohesion` - Keep related code together
- `org-circular-dependencies` - Avoid circular imports
**Key Concepts:**
- Feature-based organization
- Module boundaries
- Layer separation
- Dependency direction
- Discoverability
**When to Apply:**
- Starting new projects
- Restructuring existing codebases
- Scaling applications
- Onboarding new team members
- Managing microservices
---
## 5. Naming & Readability (MEDIUM)
**Priority:** MEDIUM
**Impact:** Code comprehension, maintenance speed
**Prefix:** `name-`
Conventions and principles for naming variables, functions, classes, and other identifiers.
### Rules (Planned)
- `name-meaningful` - Use intention-revealing names
- `name-consistent` - Follow consistent naming conventions
- `name-searchable` - Avoid magic numbers and strings
- `name-avoid-encodings` - No Hungarian notation
- `name-domain-language` - Use ubiquitous domain language
**Key Concepts:**
- Intention revelation
- Consistency
- Searchability
- Domain terminology
- Avoid abbreviations
**When to Apply:**
- Creating new identifiers
- Refactoring unclear names
- Code reviews
- Domain modeling
- API design
---
## 6. Functions & Methods (MEDIUM)
**Priority:** MEDIUM
**Impact:** Code readability, testability at function level
**Prefix:** `func-`
Principles for writing clean, focused functions and methods.
### Rules (Planned)
- `func-small` - Keep functions small and focused
- `func-single-purpose` - Do one thing only
- `func-few-arguments` - Limit function parameters
- `func-no-side-effects` - Minimize or document side effects
- `func-command-query` - Separate commands from queries
**Key Concepts:**
- Small functions
- Single purpose
- Few parameters
- Pure functions when possible
- Predictable behavior
**When to Apply:**
- Writing new functions
- Refactoring long methods
- Improving testability
- Code reviews
- Performance optimization
---
## 7. Comments & Documentation (LOW)
**Priority:** LOW
**Impact:** Code maintainability, knowledge transfer
**Prefix:** `doc-`
Guidelines for when and how to use comments and documentation effectively.
### Rules (Planned)
- `doc-self-documenting` - Write code that explains itself
- `doc-why-not-what` - Comments should explain why, not what
- `doc-avoid-noise` - No redundant or obvious comments
- `doc-api-docs` - Document public APIs and interfaces
**Key Concepts:**
- Self-documenting code
- Intent over implementation
- Avoid redundancy
- Public API documentation
- Living documentation
**When to Apply:**
- Complex business logic
- Non-obvious algorithms
- Public APIs
- Architectural decisions
- Workarounds and hacks
---
## Rule Naming Convention
All rules follow a consistent naming pattern:
```
{prefix}-{concept}-{specificity}
```
Examples:
- `solid-srp-class` - SOLID principle, SRP concept, class level
- `core-dry-extraction` - Core principle, DRY concept, extraction technique
- `pattern-repository` - Design pattern category, repository pattern
## Priority Levels Explained
- **CRITICAL**: Core architectural and coding principles. Violations significantly impact maintainability, testability, and scalability.
- **HIGH**: Important patterns and organizational principles. Violations complicate future development.
- **MEDIUM**: Best practices that improve code quality. Violations make code harder to read and maintain.
- **LOW**: Nice-to-have practices. Violations have minimal impact but reduce clarity.
## Impact Assessment
- **CRITICAL Impact**: Affects entire system architecture, multiple teams, long-term maintainability
- **HIGH Impact**: Affects module design, team productivity, medium-term maintainability
- **MEDIUM Impact**: Affects code readability, individual developer productivity
- **LOW Impact**: Affects code clarity, documentation quality
## Usage Guidelines
1. Start with SOLID and Core Principles - these are non-negotiable
2. Apply Design Patterns when solving specific architectural problems
3. Use Code Organization principles when structuring projects
4. Follow Naming & Readability guidelines for all new code
5. Apply Function principles during refactoring and new development
6. Add Comments only when necessary to explain complex logic
## Cross-References
Rules often relate to each other. The `related` field in each rule's frontmatter indicates:
- Rules that commonly apply together
- Rules that solve similar problems
- Rules that complement each other
- Rules that provide context or prerequisites
## Evolution
This categorization will evolve as:
- New rules are added
- Patterns emerge from practice
- Team feedback is incorporated
- Language-specific adaptations are needed
@@ -0,0 +1,211 @@
---
id: {prefix}-{concept}-{specificity}
title: {Full Descriptive Title}
category: {solid-principles|core-principles|design-patterns|code-organization|naming-readability|functions-methods|comments-documentation}
priority: {critical|high|medium|low}
tags: [{tag1}, {tag2}, {tag3}, {tag4}]
related: [{rule-id-1}, {rule-id-2}, {rule-id-3}]
---
# {Rule Title}
{One or two sentence summary explaining the principle and why it matters. Should be clear and actionable.}
## Bad Example
```typescript
// Anti-pattern: {Brief description of what's wrong}
{Code example demonstrating the violation}
// Problems:
// 1. {Specific issue 1}
// 2. {Specific issue 2}
// 3. {Specific issue 3}
```
**Why This Is Wrong:**
- {Consequence 1}
- {Consequence 2}
- {Consequence 3}
## Good Example
```typescript
// Correct approach: {Brief description of the solution}
{Code example demonstrating proper implementation}
// Benefits:
// 1. {Benefit 1}
// 2. {Benefit 2}
// 3. {Benefit 3}
```
**Alternative Approach (Optional):**
```typescript
// Another valid solution: {When this might be preferred}
{Alternative code example if applicable}
```
## Why
Explanation of the principle and its benefits:
1. **{Benefit Category 1}**: {Detailed explanation}
2. **{Benefit Category 2}**: {Detailed explanation}
3. **{Benefit Category 3}**: {Detailed explanation}
4. **{Benefit Category 4}**: {Detailed explanation}
5. **{Benefit Category 5}**: {Detailed explanation}
6. **{Benefit Category 6}**: {Detailed explanation}
7. **{Benefit Category 7}**: {Detailed explanation}
## When to Apply
- {Situation 1}
- {Situation 2}
- {Situation 3}
- {Situation 4}
## When NOT to Apply (Optional)
```typescript
// Acceptable exception: {Scenario where the rule can be relaxed}
{Code example of acceptable violation with clear reasoning}
// This is acceptable because:
// - {Reason 1}
// - {Reason 2}
```
## Common Mistakes (Optional)
### Mistake 1: {Common misunderstanding}
```typescript
// ❌ Wrong
{Code showing mistake}
// ✅ Correct
{Code showing correction}
```
### Mistake 2: {Another common issue}
```typescript
// ❌ Wrong
{Code showing mistake}
// ✅ Correct
{Code showing correction}
```
## Testing Implications (Optional)
How this principle affects testing:
```typescript
// Test example showing improved testability
{Test code demonstrating benefits}
```
## Real-World Example (Optional)
{Brief description of how this applies in production scenarios}
```typescript
// Production scenario: {Description}
{Realistic code example}
```
## Related Principles
- **{Related Rule 1}**: {Brief explanation of relationship}
- **{Related Rule 2}**: {Brief explanation of relationship}
- **{Related Rule 3}**: {Brief explanation of relationship}
## Further Reading (Optional)
- {Resource title} - {URL or reference}
- {Resource title} - {URL or reference}
## Language-Specific Notes (Optional)
### TypeScript/JavaScript
{Language-specific considerations}
### Python
{Language-specific considerations}
### Java
{Language-specific considerations}
### Go
{Language-specific considerations}
---
## Template Guidelines
### Frontmatter
- **id**: Use format `{prefix}-{concept}-{specificity}`. Must be unique and match filename.
- **title**: Full descriptive title, human-readable
- **category**: One of the 7 defined categories
- **priority**: critical (SOLID, Core) | high (Patterns, Org) | medium (Naming, Functions) | low (Comments)
- **tags**: 3-5 relevant tags for searchability
- **related**: 2-4 related rule IDs that commonly apply together
### Content Structure
1. **Title & Summary**: Clear, one-sentence explanation
2. **Bad Example**: Show the anti-pattern with clear problems listed
3. **Good Example**: Show proper implementation with benefits
4. **Why**: 5-7 benefits explaining the value
5. **When to Apply**: Practical scenarios
6. **Optional Sections**: Add as needed for complex rules
### Code Examples
- Use TypeScript for primary examples (language-agnostic)
- Keep examples focused and minimal
- Show realistic scenarios, not toy examples
- Include comments explaining key points
- Use ❌ for bad examples, ✅ for good examples
### Writing Style
- Be direct and actionable
- Focus on "why" not just "what"
- Use active voice
- Keep explanations concise
- Provide context for decisions
- Assume intermediate developer knowledge
### Length Guidelines
- Minimum: 200 lines (simple rules)
- Target: 300-400 lines (most rules)
- Maximum: 600 lines (complex patterns)
### Quality Checklist
- [ ] Frontmatter complete and accurate
- [ ] Clear bad example with explained problems
- [ ] Clear good example with explained benefits
- [ ] At least 5 benefits in "Why" section
- [ ] Practical "When to Apply" scenarios
- [ ] Related rules referenced
- [ ] Code examples are realistic
- [ ] Comments explain key concepts
- [ ] Language-agnostic where possible
- [ ] Proofread for clarity and typos
@@ -1,3 +1,12 @@
---
id: core-composition
title: Composition Over Inheritance
category: core-principles
priority: critical
tags: [composition, inheritance, flexibility, design]
related: [solid-srp-class, solid-dip-injection, core-encapsulation]
---
# Composition Over Inheritance
Favor composing objects from smaller, focused pieces over building deep inheritance hierarchies. Composition provides more flexibility, better encapsulation, and avoids the fragile base class problem.
@@ -1,4 +1,13 @@
# DRY Principle - Code Extraction
---
id: core-dry-extraction
title: DRY - Code Extraction
category: core-principles
priority: critical
tags: [DRY, refactoring, extraction, code-reuse]
related: [core-dry, core-dry-single-source, solid-srp-function]
---
# DRY - Code Extraction
Don't Repeat Yourself. When you find duplicated code, extract it into a reusable function, method, or module. Every piece of knowledge should have a single, unambiguous representation.
@@ -1,4 +1,13 @@
# DRY Principle - Single Source of Truth
---
id: core-dry-single-source
title: DRY - Single Source of Truth
category: core-principles
priority: critical
tags: [DRY, single-source-of-truth, constants, configuration]
related: [core-dry, core-dry-extraction, core-encapsulation]
---
# DRY - Single Source of Truth
Every piece of knowledge or configuration should exist in exactly one place. When data or logic needs to be referenced from multiple locations, use a single authoritative source.
@@ -1,7 +1,13 @@
# core-dry
---
id: core-dry
title: Don't Repeat Yourself (DRY)
category: core-principles
priority: critical
tags: [DRY, duplication, single-source-of-truth, maintainability]
related: [core-dry-extraction, core-dry-single-source, solid-srp-class]
---
**Priority:** CRITICAL
**Category:** Core Principles
# Don't Repeat Yourself (DRY)
## Why It Matters
@@ -1,3 +1,12 @@
---
id: core-encapsulation
title: Encapsulation
category: core-principles
priority: critical
tags: [encapsulation, information-hiding, data-protection]
related: [solid-srp-class, core-law-demeter, solid-isp-interfaces]
---
# Encapsulation
Hide internal implementation details and expose only what's necessary through a well-defined interface. Protect data integrity by controlling access to internal state.
@@ -1,3 +1,12 @@
---
id: core-fail-fast
title: Fail Fast Principle
category: core-principles
priority: critical
tags: [fail-fast, error-handling, validation]
related: [solid-lsp-preconditions, core-encapsulation]
---
# Fail Fast Principle
Detect and report errors as early as possible. Validate inputs at system boundaries, check preconditions at the start of functions, and throw exceptions immediately when something is wrong.
@@ -1,4 +1,13 @@
# KISS Principle - Readability
---
id: core-kiss-readability
title: KISS - Readability
category: core-principles
priority: critical
tags: [KISS, readability, clear-code, maintainability]
related: [core-kiss-simplicity, solid-srp-function]
---
# KISS - Readability
Code is read far more often than it is written. Optimize for readability by using clear names, straightforward logic, and avoiding clever tricks that obscure intent.
@@ -1,3 +1,12 @@
---
id: core-kiss-simplicity
title: KISS - Simplicity
category: core-principles
priority: critical
tags: [KISS, simplicity, over-engineering, maintainability]
related: [core-kiss-readability, core-yagni-abstractions, solid-srp-function]
---
# KISS Principle - Simplicity
Keep It Simple, Stupid. Choose the simplest solution that solves the problem. Avoid unnecessary complexity, over-engineering, and clever code that's hard to understand.
@@ -1,3 +1,12 @@
---
id: core-law-demeter
title: Law of Demeter
category: core-principles
priority: critical
tags: [law-of-demeter, coupling, encapsulation]
related: [core-encapsulation, solid-srp-class, core-separation-concerns]
---
# Law of Demeter
A method should only talk to its immediate friends, not to strangers. Don't reach through objects to access their internal structure. This reduces coupling and makes code more maintainable.
@@ -1,3 +1,12 @@
---
id: core-separation-concerns
title: Separation of Concerns
category: core-principles
priority: critical
tags: [separation-of-concerns, modularity, cohesion]
related: [solid-srp-class, solid-srp-function, core-law-demeter]
---
# Separation of Concerns
Different concerns should be handled by different parts of the system. Each module, class, or function should address a single concern, making the code easier to understand, test, and modify.
@@ -1,3 +1,12 @@
---
id: core-yagni-abstractions
title: YAGNI - Abstractions
category: core-principles
priority: critical
tags: [YAGNI, premature-abstraction, simplicity]
related: [core-yagni-features, core-kiss-simplicity, solid-ocp-abstraction]
---
# YAGNI Principle - Abstractions
Don't create abstractions until you have concrete evidence they're needed. Premature abstraction leads to wrong abstractions that are worse than no abstraction.
@@ -1,3 +1,12 @@
---
id: core-yagni-features
title: YAGNI - Features
category: core-principles
priority: critical
tags: [YAGNI, speculative-features, lean-development]
related: [core-yagni-abstractions, core-kiss-simplicity]
---
# YAGNI Principle - Features
You Aren't Gonna Need It. Don't implement features until they are actually required. Building speculative features wastes time and adds unnecessary complexity.
@@ -1,7 +1,13 @@
# pattern-repository
---
id: pattern-repository
title: Design Pattern - Repository
category: design-patterns
priority: high
tags: [design-patterns, repository, data-access, separation-of-concerns]
related: [solid-dip-abstractions, solid-srp-class, core-separation-concerns]
---
**Priority:** HIGH
**Category:** Design Patterns
# Repository Pattern
## Why It Matters
@@ -1,3 +1,12 @@
---
id: solid-dip-abstractions
title: SOLID - Dependency Inversion (Abstractions)
category: solid-principles
priority: critical
tags: [SOLID, DIP, dependency-inversion, abstractions]
related: [solid-dip-injection, solid-ocp-abstraction, pattern-repository]
---
# Dependency Inversion Principle - Depend on Abstractions
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions.
@@ -1,3 +1,12 @@
---
id: solid-dip-injection
title: SOLID - Dependency Inversion (Injection)
category: solid-principles
priority: critical
tags: [SOLID, DIP, dependency-injection, testability]
related: [solid-dip-abstractions, solid-srp-class, core-composition]
---
# Dependency Inversion Principle - Dependency Injection
Dependencies should be injected from outside rather than created inside a class. This enables loose coupling, testability, and flexibility in how dependencies are provided.
@@ -1,3 +1,12 @@
---
id: solid-isp-clients
title: SOLID - Interface Segregation (Client-Specific)
category: solid-principles
priority: critical
tags: [SOLID, ISP, interface-segregation, client-design]
related: [solid-isp-interfaces, solid-srp-class, solid-lsp-contracts]
---
# Interface Segregation Principle - Client-Specific Interfaces
Clients should not be forced to depend on interfaces they do not use. Design interfaces from the client's perspective, not the implementation's.
@@ -1,3 +1,12 @@
---
id: solid-isp-interfaces
title: SOLID - Interface Segregation (Small Interfaces)
category: solid-principles
priority: critical
tags: [SOLID, ISP, interface-segregation, cohesion]
related: [solid-isp-clients, solid-srp-class, core-separation-concerns]
---
# Interface Segregation Principle - Small Cohesive Interfaces
Interfaces should be small and cohesive, grouping only closely related methods. Split large interfaces into smaller, more focused ones.
@@ -1,3 +1,12 @@
---
id: solid-lsp-contracts
title: SOLID - Liskov Substitution (Contracts)
category: solid-principles
priority: critical
tags: [SOLID, LSP, liskov-substitution, contracts]
related: [solid-lsp-preconditions, solid-ocp-abstraction, core-composition]
---
# Liskov Substitution Principle - Contracts
Subtypes must be substitutable for their base types without altering the correctness of the program. Derived classes must honor the contracts established by their base classes.
@@ -1,3 +1,12 @@
---
id: solid-lsp-preconditions
title: SOLID - Liskov Substitution (Preconditions)
category: solid-principles
priority: critical
tags: [SOLID, LSP, liskov-substitution, preconditions, postconditions]
related: [solid-lsp-contracts, core-fail-fast, solid-ocp-abstraction]
---
# Liskov Substitution Principle - Preconditions and Postconditions
Subtypes cannot strengthen preconditions (require more) or weaken postconditions (guarantee less) compared to their base types.
@@ -1,3 +1,12 @@
---
id: solid-ocp-abstraction
title: SOLID - Open/Closed (Abstraction)
category: solid-principles
priority: critical
tags: [SOLID, OCP, open-closed, abstraction]
related: [solid-ocp-extension, solid-dip-abstractions, pattern-repository]
---
# Open/Closed Principle - Abstraction
Use abstractions (interfaces and abstract classes) to define stable contracts that allow new implementations without modifying existing code.
@@ -1,3 +1,12 @@
---
id: solid-ocp-extension
title: SOLID - Open/Closed Principle (Extension)
category: solid-principles
priority: critical
tags: [SOLID, OCP, open-closed, extensibility, design-patterns]
related: [solid-ocp-abstraction, pattern-repository, solid-dip-abstractions]
---
# Open/Closed Principle - Extension
Software entities should be open for extension but closed for modification. Add new functionality by adding new code, not by changing existing code.
@@ -1,3 +1,12 @@
---
id: solid-srp-class
title: SOLID - Single Responsibility Principle (Class Level)
category: solid-principles
priority: critical
tags: [SOLID, SRP, single-responsibility, class-design]
related: [solid-srp-function, core-separation-concerns, solid-isp-interfaces]
---
# Single Responsibility Principle - Class Level
A class should have only one reason to change, meaning it should have only one job or responsibility.
@@ -1,3 +1,12 @@
---
id: solid-srp-function
title: SOLID - Single Responsibility Principle (Function Level)
category: solid-principles
priority: critical
tags: [SOLID, SRP, single-responsibility, function-design]
related: [solid-srp-class, core-dry-extraction, core-kiss-simplicity]
---
# Single Responsibility Principle - Function Level
A function should do one thing, do it well, and do it only. It should have a single, clear purpose that can be described without using conjunctions like "and" or "or".
+453
View File
@@ -0,0 +1,453 @@
# Git Workflow - Agent Guidelines
This document provides guidance for AI agents on how to effectively use the git-workflow skill to review and improve git practices in codebases.
## Skill Overview
**Purpose:** Help teams maintain excellent git hygiene through commit conventions, branching strategies, and PR workflows.
**When to Use:**
- Reviewing commit messages for clarity and convention compliance
- Analyzing branching strategies and suggesting improvements
- Evaluating pull request practices and templates
- Auditing git history for cleanliness and maintainability
- Setting up git workflows for new or existing projects
- Troubleshooting git collaboration issues
## Agent Capabilities
### 1. Commit Message Analysis
**What to Check:**
- Conventional commit format compliance
- Subject line clarity and length (50 char ideal, 72 max)
- Imperative mood usage
- Body presence and quality for complex changes
- Issue/PR references
- Breaking change documentation
**Example Analysis:**
```
Input: "fixed bug in login"
Agent Response:
[commit] Use conventional commit format: "fix(auth): resolve login timeout issue"
[commit] Add commit body explaining the root cause and solution
[commit] Reference the related issue: "Fixes #123"
```
### 2. Branch Strategy Evaluation
**What to Check:**
- Branch naming conventions
- Branch protection on main/master
- Feature branch workflow adoption
- Branch lifecycle (short-lived vs long-lived)
- Cleanup of merged branches
- Release branch strategy
**Example Analysis:**
```
Input: Repository with 50+ stale merged branches and inconsistent naming
Agent Response:
[branch] 45 merged branches still exist - implement automatic deletion
[branch] Inconsistent naming detected (fix-bug, feature_new, FIX-123) - adopt consistent convention
[branch] Main branch lacks protection - enable PR requirements and CI checks
```
### 3. Pull Request Review
**What to Check:**
- PR size (lines changed, files modified)
- Description quality and template usage
- Reviewer assignment strategy
- CI check requirements
- Merge strategy consistency
- Draft PR usage for WIP
**Example Analysis:**
```
Input: PR with 2000+ lines, no description, bypassing CI
Agent Response:
[pr] PR is too large (2000+ lines, 50 files) - consider splitting into smaller PRs
[pr] Missing PR description - add context, testing notes, and related issues
[pr] CI checks failed but merge was forced - require CI passing before merge
```
### 4. History Management Review
**What to Check:**
- Rebase vs merge strategy appropriateness
- Force push patterns on shared branches
- Commit cleanliness before merging
- Tag usage for releases
- Semantic versioning compliance
**Example Analysis:**
```
Input: Multiple force pushes to main, inconsistent merge strategy, no release tags
Agent Response:
[history] 5 force pushes detected on main branch - disable force push and use revert instead
[history] Mixing merge and rebase strategies - adopt consistent squash merge for PRs
[history] No release tags found - implement semantic versioning with annotated tags
```
### 5. Collaboration Assessment
**What to Check:**
- Code review practices
- Merge conflict resolution patterns
- Team communication through git
- CODEOWNERS file usage
- Review response times
## Analysis Workflow
### Step 1: Context Gathering
```
1. Identify repository platform (GitHub, GitLab, etc.)
2. Check repository size and team structure
3. Review existing git configuration
4. Examine recent commit history (last 50-100 commits)
5. Analyze open and recent PRs
```
### Step 2: Rule Application
```
1. Start with CRITICAL priority rules (commit messages)
2. Move to HIGH priority rules (branching, PRs)
3. Finish with MEDIUM priority rules (history, collaboration)
4. Consider project context and team size
```
### Step 3: Findings Presentation
```
Format: [category] Description of issue or recommendation
Priority order:
1. Critical issues affecting team workflow
2. High-impact improvements
3. Nice-to-have enhancements
Include:
- Specific examples from the codebase
- Concrete recommendations
- Configuration snippets when applicable
```
## Common Patterns and Solutions
### Pattern: Messy Commit History
**Indicators:**
- WIP commits in main branch
- No conventional commit format
- Commit messages like "fix", "update", "changes"
**Solution:**
```bash
# Implement commitlint
npm install --save-dev @commitlint/cli @commitlint/config-conventional
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
# Setup git hooks with husky
npm install --save-dev husky
npx husky install
echo '#!/bin/sh\nnpx commitlint --edit $1' > .husky/commit-msg
# Use squash merge for PRs
gh api repos/:owner/:repo --method PATCH -f squash_merge_commit_title=PR_TITLE
```
### Pattern: Unprotected Main Branch
**Indicators:**
- Direct pushes to main
- No required reviews
- CI bypassed
- Force push allowed
**Solution:**
```bash
# Enable branch protection via GitHub CLI
gh api repos/:owner/:repo/branches/main/protection --method PUT --input - <<EOF
{
"required_pull_request_reviews": {
"required_approving_review_count": 1,
"dismiss_stale_reviews": true
},
"required_status_checks": {
"strict": true,
"contexts": ["ci/test", "ci/lint"]
},
"enforce_admins": true,
"restrictions": null,
"allow_force_pushes": false
}
EOF
```
### Pattern: Large, Unfocused PRs
**Indicators:**
- PRs with 1000+ lines changed
- Multiple unrelated changes
- Slow review cycles
- High conflict rate
**Solution:**
```markdown
# Create PR template
## .github/PULL_REQUEST_TEMPLATE.md
## Summary
Brief description (1-2 sentences)
## Changes
- Focused list of changes
- Max 5-10 items suggests good scope
## Size Guidelines
- ✅ Small: < 200 lines
- ⚠️ Medium: 200-400 lines
- ❌ Large: > 400 lines (should be split)
## Testing
- [ ] Unit tests added/updated
- [ ] Manual testing completed
- [ ] No breaking changes OR migration guide included
## Related Issues
Fixes #issue-number
```
### Pattern: Inconsistent Branch Naming
**Indicators:**
- Branches named "test", "fix", "my-branch"
- Mix of formats (snake_case, PascalCase, kebab-case)
- No type prefixes
**Solution:**
```bash
# Document branch naming convention in CONTRIBUTING.md
# Enforce with CI check
# .github/workflows/branch-naming.yml
name: Branch Naming
on: pull_request
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Check branch name
run: |
if [[ ! "${{ github.head_ref }}" =~ ^(feature|fix|hotfix|refactor|docs|test|chore)/.+ ]]; then
echo "Branch name must match pattern: type/description"
echo "Valid types: feature, fix, hotfix, refactor, docs, test, chore"
exit 1
fi
```
## Example Workflows
### Scenario 1: New Project Setup
```
Agent Task: "Set up git workflow for new team repository"
Actions:
1. Create commitlint.config.js with conventional commits
2. Set up Husky hooks for commit-msg validation
3. Create PR template in .github/PULL_REQUEST_TEMPLATE.md
4. Configure branch protection for main
5. Create CONTRIBUTING.md with git guidelines
6. Set up semantic-release for automated versioning
7. Document workflow in README.md
Deliverable: "Git workflow configured with conventional commits,
PR templates, branch protection, and automated releases"
```
### Scenario 2: Git History Audit
```
Agent Task: "Review last 100 commits and identify git hygiene issues"
Analysis Steps:
1. Check commit message format
git log --oneline -100 --format="%s" | analyze format
2. Identify WIP/fixup commits in main
git log -100 --grep="WIP\|fixup\|wip" --oneline
3. Check for force pushes
git reflog main | grep "force"
4. Analyze commit size distribution
git log -100 --stat | analyze changes
5. Review merge commit patterns
git log -100 --merges --oneline
Output: Categorized findings with specific examples and recommendations
```
### Scenario 3: PR Workflow Optimization
```
Agent Task: "Improve PR workflow for faster reviews"
Recommendations:
1. Implement PR size checks in CI
2. Set up CODEOWNERS for automatic reviewer assignment
3. Create PR templates for different change types
4. Configure required status checks
5. Set up draft PR workflow documentation
6. Implement squash merge by default
7. Add PR metrics tracking
Outcome: "Reduced average PR review time from 3 days to 1 day"
```
## Best Practices for Agents
### DO:
- Provide specific, actionable recommendations
- Show concrete examples from the codebase
- Offer configuration snippets and commands
- Explain WHY each practice matters
- Consider team size and project context
- Prioritize critical issues first
- Link to authoritative resources
### DON'T:
- Recommend practices that don't fit the team's workflow
- Overwhelm with too many changes at once
- Suggest configuration without explaining benefits
- Ignore existing team conventions
- Apply rules dogmatically without context
- Forget to explain migration paths
## Integration Points
### With CI/CD
```yaml
# Example GitHub Actions integration
name: Git Hygiene Check
on: [pull_request]
jobs:
commit-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: wagoid/commitlint-github-action@v5
pr-size:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check PR size
run: |
FILES_CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...HEAD | wc -l)
LINES_CHANGED=$(git diff --stat origin/${{ github.base_ref }}...HEAD | tail -1 | awk '{print $4+$6}')
if [ $LINES_CHANGED -gt 500 ]; then
echo "PR is too large ($LINES_CHANGED lines). Consider splitting."
exit 1
fi
```
### With Project Tools
- **GitHub/GitLab:** Use API for branch protection, PR analysis
- **Jira/Linear:** Link commits to issues for traceability
- **Slack/Discord:** Notify team of workflow violations
- **Documentation:** Auto-generate changelog from conventional commits
## Metrics to Track
Track these metrics to measure git workflow health:
1. **Commit Quality**
- % of commits following conventional format
- Average commit message length
- % of commits with body text
2. **PR Velocity**
- Average time to first review
- Average time to merge
- Average PR size (lines, files)
3. **Branch Health**
- Number of stale branches
- Average branch lifetime
- % of branches following naming convention
4. **Release Cadence**
- Time between releases
- % of releases with proper tags
- Semantic version compliance
## Learning Resources for Agents
When providing guidance, reference these authoritative sources:
- **Git Official Docs:** https://git-scm.com/doc
- **Conventional Commits:** https://www.conventionalcommits.org
- **Pro Git Book:** https://git-scm.com/book/en/v2
- **GitHub Best Practices:** https://docs.github.com/en/get-started/quickstart/github-flow
- **Code Review Guide:** https://google.github.io/eng-practices/review/
## Output Format
Always structure your analysis as:
```
# Git Workflow Analysis
## Summary
Brief overview of findings (2-3 sentences)
## Critical Issues
[commit] Issue description with example
[branch] Issue description with example
## Recommendations
### Immediate Actions
1. [Action with command or config]
2. [Action with command or config]
### Long-term Improvements
1. [Improvement suggestion]
2. [Improvement suggestion]
## Configuration Changes
### commitlint.config.js
```javascript
// configuration
```
### .github/workflows/ci.yml
```yaml
# workflow
```
## Resources
- [Link to relevant documentation]
- [Link to example implementation]
```
---
## Agent Self-Check
Before completing analysis, verify:
- [ ] Checked all critical priority rules
- [ ] Provided specific examples from codebase
- [ ] Included actionable recommendations
- [ ] Offered configuration snippets
- [ ] Explained WHY for each suggestion
- [ ] Prioritized issues appropriately
- [ ] Considered team/project context
- [ ] Linked to authoritative resources
+120 -3
View File
@@ -447,7 +447,124 @@ Example:
Read individual rule files for detailed explanations:
```
rules/commit-conventional.md
rules/branch-naming.md
rules/pr-small.md
rules/commit-conventional-format.md
rules/branch-naming-convention.md
rules/pr-small-focused.md
```
## References
- [Git Official Documentation](https://git-scm.com/doc) - Comprehensive Git documentation
- [Pro Git Book](https://git-scm.com/book/en/v2) - The complete Pro Git book
- [Conventional Commits](https://www.conventionalcommits.org) - Commit message specification
- [GitHub Flow](https://docs.github.com/en/get-started/quickstart/github-flow) - Lightweight workflow
- [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/) - Commit message guide
- [Google Code Review Practices](https://google.github.io/eng-practices/review/) - Code review best practices
## Examples from Well-Known Projects
Learn from projects with excellent git practices:
- **Linux Kernel** - Detailed commit messages and patch workflow
- **React** - Conventional commits and thorough PR reviews
- **Vue.js** - Clean commit history and good PR templates
- **TypeScript** - Structured branching and clear release process
- **Next.js** - Conventional commits and automated releases
## Configuration Examples
### Commitlint
```javascript
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'chore', 'ci', 'build', 'revert']
],
'subject-max-length': [2, 'always', 72],
'body-max-line-length': [2, 'always', 100]
}
};
```
### Husky Git Hooks
```bash
# .husky/commit-msg
#!/bin/sh
npx commitlint --edit $1
# .husky/pre-commit
#!/bin/sh
npm run lint
npm test
```
### GitHub PR Template
```markdown
# .github/PULL_REQUEST_TEMPLATE.md
## Summary
Brief description of changes
## Changes
- List key changes
- One per line
## Testing
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing completed
## Related
Closes #issue-number
```
---
## Metadata
**Skill Version:** 1.0.0
**Last Updated:** 2026-01-17
**Total Rules:** 26
**Categories:** 5 (Commit Messages, Branching Strategy, Pull Requests, History Management, Collaboration)
**Compatible With:**
- Git 2.0+
- GitHub, GitLab, Bitbucket, Azure DevOps
**Recommended Tools:**
- [Git](https://git-scm.com/) - Version control system
- [GitHub CLI](https://cli.github.com/) - GitHub command-line tool
- [Commitlint](https://commitlint.js.org/) - Commit message linter
- [Husky](https://typicode.github.io/husky/) - Git hooks
- [Semantic Release](https://semantic-release.gitbook.io/) - Automated versioning
---
## License
MIT License
Copyright (c) 2026 Agent Skills Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+216
View File
@@ -0,0 +1,216 @@
{
"skill": {
"name": "git-workflow",
"version": "1.0.0",
"description": "Git best practices, branching strategies, commit conventions, and PR workflows",
"author": "Agent Skills Team",
"license": "MIT",
"keywords": [
"git",
"version-control",
"commits",
"branches",
"pull-requests",
"code-review",
"conventional-commits",
"git-flow",
"trunk-based-development"
]
},
"categories": [
{
"id": "commit",
"name": "Commit Messages",
"priority": "critical",
"description": "Standards for writing clear, meaningful commit messages",
"rule_count": 7
},
{
"id": "branch",
"name": "Branching Strategy",
"priority": "high",
"description": "Guidelines for creating, naming, and managing branches",
"rule_count": 6
},
{
"id": "pull-request",
"name": "Pull Requests",
"priority": "high",
"description": "Best practices for creating and reviewing pull requests",
"rule_count": 6
},
{
"id": "history",
"name": "History Management",
"priority": "medium",
"description": "Techniques for maintaining a clean, useful git history",
"rule_count": 4
},
{
"id": "collaboration",
"name": "Collaboration",
"priority": "medium",
"description": "Practices for effective team collaboration using git",
"rule_count": 3
}
],
"references": [
{
"title": "Git Official Documentation",
"url": "https://git-scm.com/doc",
"description": "Comprehensive official Git documentation covering all commands and concepts",
"type": "official"
},
{
"title": "Pro Git Book",
"url": "https://git-scm.com/book/en/v2",
"description": "The entire Pro Git book, written by Scott Chacon and Ben Straub",
"type": "book"
},
{
"title": "Conventional Commits",
"url": "https://www.conventionalcommits.org",
"description": "A specification for adding human and machine readable meaning to commit messages",
"type": "specification"
},
{
"title": "Git Best Practices",
"url": "https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project",
"description": "Official guidance on contributing to Git projects and best practices",
"type": "guide"
},
{
"title": "GitHub Flow",
"url": "https://docs.github.com/en/get-started/quickstart/github-flow",
"description": "GitHub's lightweight, branch-based workflow",
"type": "workflow"
},
{
"title": "GitFlow Workflow",
"url": "https://nvie.com/posts/a-successful-git-branching-model/",
"description": "Vincent Driessen's popular git branching model",
"type": "workflow"
},
{
"title": "Semantic Versioning",
"url": "https://semver.org/",
"description": "Versioning specification for software releases",
"type": "specification"
},
{
"title": "How to Write a Git Commit Message",
"url": "https://chris.beams.io/posts/git-commit/",
"description": "Comprehensive guide on writing great commit messages",
"type": "guide"
},
{
"title": "GitHub Pull Request Best Practices",
"url": "https://docs.github.com/en/pull-requests/collaborating-with-pull-requests",
"description": "Official GitHub documentation on pull requests and code review",
"type": "guide"
},
{
"title": "Git Merge vs Rebase",
"url": "https://www.atlassian.com/git/tutorials/merging-vs-rebasing",
"description": "Detailed comparison of merge and rebase strategies",
"type": "tutorial"
},
{
"title": "Code Review Best Practices",
"url": "https://google.github.io/eng-practices/review/",
"description": "Google's engineering practices for code review",
"type": "guide"
},
{
"title": "Trunk Based Development",
"url": "https://trunkbaseddevelopment.com/",
"description": "Source-control branching model for continuous integration",
"type": "workflow"
}
],
"tools": [
{
"name": "Git",
"url": "https://git-scm.com/",
"description": "Distributed version control system"
},
{
"name": "GitHub CLI",
"url": "https://cli.github.com/",
"description": "Command-line tool for GitHub operations"
},
{
"name": "Commitlint",
"url": "https://commitlint.js.org/",
"description": "Lint commit messages according to conventional commits"
},
{
"name": "Husky",
"url": "https://typicode.github.io/husky/",
"description": "Git hooks made easy"
},
{
"name": "Semantic Release",
"url": "https://semantic-release.gitbook.io/",
"description": "Automated version management and package publishing"
},
{
"name": "Conventional Changelog",
"url": "https://github.com/conventional-changelog/conventional-changelog",
"description": "Generate changelogs from git metadata"
}
],
"examples": {
"projects": [
{
"name": "Linux Kernel",
"url": "https://github.com/torvalds/linux",
"description": "Excellent example of detailed commit messages and patch workflow"
},
{
"name": "React",
"url": "https://github.com/facebook/react",
"description": "Conventional commits, thorough PR reviews, clear branching"
},
{
"name": "Vue.js",
"url": "https://github.com/vuejs/vue",
"description": "Clean commit history, conventional commits, good PR templates"
},
{
"name": "TypeScript",
"url": "https://github.com/microsoft/TypeScript",
"description": "Structured branching, detailed PR descriptions, clear release process"
},
{
"name": "Next.js",
"url": "https://github.com/vercel/next.js",
"description": "Conventional commits, automated releases, excellent PR workflow"
}
]
},
"configurations": {
"commitlint": {
"file": "commitlint.config.js",
"example": "module.exports = { extends: ['@commitlint/config-conventional'] };"
},
"husky": {
"file": ".husky/commit-msg",
"example": "#!/bin/sh\nnpx commitlint --edit $1"
},
"github": {
"pr_template": ".github/PULL_REQUEST_TEMPLATE.md",
"codeowners": ".github/CODEOWNERS"
}
},
"meta": {
"created": "2026-01-17",
"last_updated": "2026-01-17",
"rule_count": 26,
"structure_version": "2.0",
"compatibility": {
"git": ">=2.0.0",
"platforms": ["GitHub", "GitLab", "Bitbucket", "Azure DevOps"]
}
}
}
+135
View File
@@ -0,0 +1,135 @@
# Git Workflow Rule Sections
This document defines the organizational structure for git workflow rules.
## Section Categories
### 1. Commit Messages (commit)
**Priority:** Critical
**Description:** Standards for writing clear, meaningful commit messages that document code changes effectively.
Commit messages are the permanent record of why changes were made. Well-written commits enable:
- Automated changelog generation
- Semantic versioning
- Easier debugging with git bisect
- Code archaeology and understanding historical decisions
- Better code reviews
**Rules in this section:**
- Conventional commit format
- Atomic commits
- Imperative mood
- Meaningful subject lines
- Body for context
- Issue references
- Breaking change documentation
---
### 2. Branching Strategy (branch)
**Priority:** High
**Description:** Guidelines for creating, naming, and managing branches to enable parallel development and stable releases.
Effective branching strategies allow teams to work in parallel without conflicts while maintaining a stable main branch. This includes:
- Feature branch workflows
- Branch naming conventions
- Branch lifecycle management
- Release strategies
**Rules in this section:**
- Branch naming conventions
- Feature branch workflow
- Protected main branch
- Short-lived branches
- Delete merged branches
- Release branch strategy
---
### 3. Pull Requests (pull-request)
**Priority:** High
**Description:** Best practices for creating and reviewing pull requests to ensure code quality and knowledge sharing.
Pull requests are the primary mechanism for code review and collaboration. Good PR practices:
- Enable thorough code review
- Facilitate knowledge sharing
- Maintain code quality standards
- Document changes for future reference
**Rules in this section:**
- Small, focused PRs
- PR description templates
- Reviewer assignment
- CI checks
- Squash merge strategy
- Draft PR usage
---
### 4. History Management (history)
**Priority:** Medium
**Description:** Techniques for maintaining a clean, useful git history that aids debugging and understanding.
Git history is a valuable resource when:
- Debugging issues with git bisect
- Understanding why code exists
- Reverting problematic changes
- Onboarding new team members
**Rules in this section:**
- Rebase vs merge
- Avoiding force push on shared branches
- Cleaning up commits
- Tags and releases
---
### 5. Collaboration (collaboration)
**Priority:** Medium
**Description:** Practices for effective team collaboration using git workflows and communication.
Successful git collaboration requires:
- Effective code review practices
- Clear communication
- Conflict resolution skills
- Team coordination
**Rules in this section:**
- Code review best practices
- Merge conflict resolution
- Team communication
---
## Priority Levels
| Priority | When to Apply | Impact |
|----------|---------------|--------|
| **Critical** | Always enforce | Core to git workflow success, affects entire team |
| **High** | Enforce on most projects | Significant quality and collaboration impact |
| **Medium** | Context-dependent | Important but may vary by team/project |
## Category Relationships
```
Commit Messages (critical)
↓ forms foundation for
Pull Requests (high)
↓ reviewed through
Collaboration (medium)
↓ coordinates
Branching Strategy (high)
↓ managed via
History Management (medium)
```
## Using These Sections
When reviewing git practices:
1. Start with **Commit Messages** - the foundation
2. Check **Branching Strategy** - the structure
3. Review **Pull Requests** - the process
4. Verify **History Management** - the maintenance
5. Assess **Collaboration** - the team dynamics
Each section builds on the previous ones to create a comprehensive git workflow.
+119
View File
@@ -0,0 +1,119 @@
---
title: [Rule Title]
category: [commit|branch|pull-request|history|collaboration]
priority: [critical|high|medium]
tags: [tag1, tag2, tag3, tag4]
related: [related-rule-1, related-rule-2, related-rule-3]
---
# [Rule Title]
[One-sentence description of what this rule is about and why it matters]
## Bad Example
```bash
# [Description of the bad practice]
git command that demonstrates the problem
# Comments explaining why this is problematic
# [Another example of the bad practice]
git command that shows another anti-pattern
# More context about the issue
```
## Good Example
```bash
# [Description of the good practice]
git command that demonstrates the solution
# Comments explaining why this works well
# [Another example of the good practice]
git command that shows best practice
# More context about the benefits
# [Advanced or comprehensive example]
git command sequence for complete workflow
# Detailed explanation of the approach
```
## Why
[Explanation of why this rule matters, with specific benefits]
1. **[Benefit 1]**: Description of first major benefit
2. **[Benefit 2]**: Description of second major benefit
3. **[Benefit 3]**: Description of third major benefit
4. **[Benefit 4]**: Description of fourth major benefit
5. **[Benefit 5]**: Description of fifth major benefit
[Additional context about the rule:]
| Aspect | Detail |
|--------|--------|
| When to use | [Situations where this rule applies] |
| When NOT to use | [Exceptions or special cases] |
| Team size | [How this scales with team size] |
| Project type | [Project types this applies to] |
[Practical guidelines or checklist:]
- [Guideline 1]
- [Guideline 2]
- [Guideline 3]
- [Guideline 4]
[Optional: Configuration or automation:]
```bash
# Tool configuration
# Example: .gitconfig, GitHub settings, CI configuration
```
[Optional: Related commands or workflow:]
```bash
# Useful related commands
git command --options
# Explanation
# Common troubleshooting
git command to fix issues
# When to use this
```
---
## Template Guidelines
### YAML Frontmatter
- **title**: Clear, concise rule name
- **category**: One of: commit, branch, pull-request, history, collaboration
- **priority**: critical (always enforce), high (most projects), medium (context-dependent)
- **tags**: 3-5 descriptive tags for searchability
- **related**: 2-4 related rules that connect to this one
### Bad Example Section
- Show 2-3 concrete anti-patterns
- Use real git commands
- Add inline comments explaining the problem
- Be specific about why it's bad
### Good Example Section
- Show 2-3 correct approaches
- Use real git commands that work
- Add inline comments explaining benefits
- Progress from simple to comprehensive examples
### Why Section
- List 4-5 concrete benefits
- Use bold headers for each benefit
- Include a comparison table if helpful
- Add practical guidelines as bullet points
- Show configuration/automation when relevant
### General Writing Guidelines
- Use imperative mood for commands ("Do this", not "You should do this")
- Be specific and actionable
- Include real-world context
- Show both the problem and solution
- Focus on git best practices, commit conventions, PR workflows
- Use good git examples from well-known projects
@@ -1,3 +1,11 @@
---
title: Delete Merged Branches
category: branch
priority: high
tags: [branching, cleanup, maintenance, automation]
related: [branch-short-lived, branch-feature-workflow]
---
# Delete Merged Branches
Clean up branches after they've been merged to keep the repository tidy and navigable.
@@ -1,3 +1,11 @@
---
title: Feature Branch Workflow
category: branch
priority: high
tags: [branching, workflow, feature-branches, isolation]
related: [branch-naming-convention, branch-short-lived, pr-small-focused]
---
# Feature Branch Workflow
Develop new features in dedicated branches, keeping main stable and deployable at all times.
@@ -1,3 +1,11 @@
---
title: Protected Main Branch
category: branch
priority: high
tags: [branching, protection, security, quality-gates]
related: [branch-feature-workflow, pr-ci-checks, collab-code-review]
---
# Protected Main Branch
The main branch should be protected from direct pushes and require pull requests for all changes.
@@ -1,3 +1,11 @@
---
title: Branch Naming Convention
category: branch
priority: high
tags: [branching, naming, conventions, automation]
related: [branch-feature-workflow, commit-conventional-format]
---
# Branch Naming Convention
Use consistent, descriptive branch names that indicate the type and purpose of the work.
@@ -1,3 +1,11 @@
---
title: Release Branch Strategy
category: branch
priority: high
tags: [branching, releases, deployment, versioning]
related: [history-tags-releases, branch-feature-workflow, commit-breaking-changes]
---
# Release Branch Strategy
Use a consistent branching strategy for releases that fits your deployment model and team size.
@@ -1,3 +1,11 @@
---
title: Short-Lived Branches
category: branch
priority: high
tags: [branching, merge-conflicts, feature-flags, continuous-integration]
related: [branch-feature-workflow, pr-small-focused, history-rebase-vs-merge]
---
# Short-Lived Branches
Keep feature branches short-lived to minimize merge conflicts and integration challenges.
@@ -1,3 +1,11 @@
---
title: Code Review Best Practices
category: collaboration
priority: medium
tags: [collaboration, code-review, feedback, quality]
related: [pr-reviewers, pr-description-template, pr-small-focused]
---
# Code Review Best Practices
Conduct thorough, constructive code reviews that improve code quality and share knowledge.
@@ -1,3 +1,11 @@
---
title: Team Communication in Git Workflows
category: collaboration
priority: medium
tags: [collaboration, communication, coordination, team-work]
related: [pr-description-template, collab-code-review, branch-feature-workflow]
---
# Team Communication in Git Workflows
Communicate effectively with your team through commits, PRs, and related tools to maintain smooth collaboration.
@@ -1,3 +1,11 @@
---
title: Merge Conflict Resolution
category: collaboration
priority: medium
tags: [collaboration, merge-conflicts, resolution, testing]
related: [history-rebase-vs-merge, branch-short-lived]
---
# Merge Conflict Resolution
Handle merge conflicts carefully and systematically to maintain code integrity.
@@ -1,3 +1,11 @@
---
title: Atomic Commits
category: commit
priority: critical
tags: [commits, atomic, best-practices, revert]
related: [commit-meaningful-subject, history-clean-commits]
---
# Atomic Commits
Each commit should represent a single, complete, logical change that can be understood and reverted independently.
@@ -1,3 +1,11 @@
---
title: Commit Body for Context
category: commit
priority: critical
tags: [commits, documentation, context, motivation]
related: [commit-meaningful-subject, commit-references]
---
# Commit Body for Context
Use the commit body to explain the motivation behind changes and provide additional context that isn't obvious from the code.
@@ -1,3 +1,11 @@
---
title: Documenting Breaking Changes
category: commit
priority: critical
tags: [commits, breaking-changes, semver, migration]
related: [commit-conventional-format, commit-body-context]
---
# Documenting Breaking Changes
Clearly mark and document breaking changes that require consumers to modify their code or configuration.
@@ -1,3 +1,11 @@
---
title: Conventional Commit Format
category: commit
priority: critical
tags: [commits, conventional-commits, standards, automation]
related: [commit-meaningful-subject, commit-references, commit-breaking-changes]
---
# Conventional Commit Format
Use the Conventional Commits specification for standardized, machine-readable commit messages.
@@ -1,3 +1,11 @@
---
title: Imperative Mood in Commit Messages
category: commit
priority: critical
tags: [commits, writing-style, conventions, grammar]
related: [commit-conventional-format, commit-meaningful-subject]
---
# Imperative Mood in Commit Messages
Write commit messages in the imperative mood, as if giving a command or instruction.
@@ -1,3 +1,11 @@
---
title: Meaningful Commit Subject Lines
category: commit
priority: critical
tags: [commits, subject-line, clarity, documentation]
related: [commit-conventional-format, commit-imperative-mood, commit-body-context]
---
# Meaningful Commit Subject Lines
Write clear, descriptive subject lines that explain WHAT changed and WHY it matters.
@@ -1,3 +1,11 @@
---
title: Issue and PR References in Commits
category: commit
priority: critical
tags: [commits, traceability, issues, automation]
related: [commit-body-context, commit-conventional-format]
---
# Issue and PR References in Commits
Link commits to relevant issues, pull requests, and external resources for traceability.
@@ -1,3 +1,11 @@
---
title: Clean Up Commits Before Merging
category: history
priority: medium
tags: [history, interactive-rebase, cleanup, code-review]
related: [history-rebase-vs-merge, commit-atomic-changes, pr-squash-merge]
---
# Clean Up Commits Before Merging
Use interactive rebase to clean up commit history before creating or merging a pull request.
@@ -1,3 +1,11 @@
---
title: Avoid Force Push on Shared Branches
category: history
priority: medium
tags: [history, force-push, safety, collaboration]
related: [history-rebase-vs-merge, branch-main-protected]
---
# Avoid Force Push on Shared Branches
Never force push to shared branches like main or develop, as it rewrites history and disrupts other developers.
@@ -1,3 +1,11 @@
---
title: Rebase vs. Merge
category: history
priority: medium
tags: [history, rebase, merge, workflow]
related: [history-no-force-push, branch-feature-workflow, pr-squash-merge]
---
# Rebase vs. Merge
Understand when to use rebase versus merge to maintain a clean and useful git history.
@@ -1,3 +1,11 @@
---
title: Tags and Releases
category: history
priority: medium
tags: [history, tags, releases, versioning, semver]
related: [branch-release-strategy, commit-breaking-changes]
---
# Tags and Releases
Use annotated tags to mark releases and maintain a clear versioning history.
@@ -1,3 +1,11 @@
---
title: CI Checks Must Pass
category: pull-request
priority: high
tags: [pull-requests, ci-cd, quality-gates, automation]
related: [pr-small-focused, branch-main-protected]
---
# CI Checks Must Pass
All continuous integration checks must pass before a pull request can be merged.
@@ -1,3 +1,11 @@
---
title: PR Description Template
category: pull-request
priority: high
tags: [pull-requests, documentation, templates, communication]
related: [pr-small-focused, pr-reviewers, commit-body-context]
---
# PR Description Template
Use a consistent, informative template for pull request descriptions to aid reviewers and document changes.
@@ -1,3 +1,11 @@
---
title: Draft Pull Requests
category: pull-request
priority: high
tags: [pull-requests, collaboration, work-in-progress, early-feedback]
related: [pr-description-template, pr-ci-checks]
---
# Draft Pull Requests
Use draft PRs to share work-in-progress, get early feedback, and run CI before requesting formal review.
@@ -1,3 +1,11 @@
---
title: Requesting and Assigning Reviewers
category: pull-request
priority: high
tags: [pull-requests, code-review, collaboration, codeowners]
related: [pr-description-template, collab-code-review]
---
# Requesting and Assigning Reviewers
Thoughtfully select reviewers who can provide valuable feedback on your changes.
@@ -1,3 +1,11 @@
---
title: Small, Focused Pull Requests
category: pull-request
priority: high
tags: [pull-requests, code-review, velocity, quality]
related: [pr-description-template, branch-short-lived, commit-atomic-changes]
---
# Small, Focused Pull Requests
Keep pull requests small and focused on a single concern to enable thorough reviews and reduce risk.
@@ -1,3 +1,11 @@
---
title: Squash Merge Strategy
category: pull-request
priority: high
tags: [pull-requests, merge-strategy, history, changelog]
related: [history-clean-commits, history-rebase-vs-merge, commit-conventional-format]
---
# Squash Merge Strategy
Use squash merging to maintain a clean, linear history while preserving development context in PRs.
File diff suppressed because it is too large Load Diff
+44 -47
View File
@@ -1,6 +1,12 @@
---
name: laravel-best-practices
description: Laravel 12 conventions and best practices. Use when creating controllers, models, migrations, validation, services, or structuring Laravel applications. Triggers on tasks involving Laravel architecture, Eloquent, database, API development, or PHP patterns.
license: MIT
metadata:
author: Laravel Community
version: "1.0.0"
laravelVersion: "12.x"
phpVersion: "8.5+"
---
# Laravel 12 Best Practices
@@ -21,82 +27,67 @@ Reference these guidelines when:
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Architecture & Structure | CRITICAL | `arch-` |
| 2 | Eloquent & Database | CRITICAL | `db-` |
| 3 | Controllers & Routing | HIGH | `ctrl-` |
| 4 | Validation & Requests | HIGH | `valid-` |
| 2 | Eloquent & Database | CRITICAL | `eloquent-` |
| 3 | Controllers & Routing | HIGH | `controller-`, `ctrl-` |
| 4 | Validation & Requests | HIGH | `validation-`, `valid-` |
| 5 | Security | HIGH | `sec-` |
| 6 | Performance | MEDIUM | `perf-` |
| 7 | API Design | MEDIUM | `api-` |
| 8 | Testing | LOW-MEDIUM | `test-` |
## Quick Reference
### 1. Architecture & Structure (CRITICAL)
- `arch-single-responsibility` - One job per class
- `arch-service-classes` - Extract business logic to services
- `arch-action-classes` - Single-purpose action classes
- `arch-repository-pattern` - When to use repositories
- `arch-dto-pattern` - Data transfer objects
- `arch-folder-structure` - Organize by domain/feature
- `arch-value-objects` - Encapsulate domain concepts
- `arch-event-driven` - Decouple with events and listeners
- `arch-feature-folders` - Organize by domain/feature
### 2. Eloquent & Database (CRITICAL)
- `db-eager-loading` - Prevent N+1 queries
- `db-chunking` - Process large datasets
- `db-query-scopes` - Reusable query logic
- `db-model-events` - Use observers for side effects
- `db-migrations` - Migration best practices
- `db-indexes` - Proper indexing strategy
- `eloquent-eager-loading` - Prevent N+1 queries
- `eloquent-chunking` - Process large datasets
- `eloquent-query-scopes` - Reusable query logic
- `eloquent-model-events` - Use observers for side effects
- `eloquent-relationships` - Define relationships properly
- `eloquent-casts` - Automatic attribute casting
- `eloquent-accessors-mutators` - Transform attributes
- `eloquent-soft-deletes` - Safe deletion with recovery
- `eloquent-pruning` - Automatic cleanup of old records
### 3. Controllers & Routing (HIGH)
- `ctrl-resource-controllers` - Use resource controllers
- `ctrl-thin-controllers` - Keep controllers thin
- `ctrl-route-model-binding` - Implicit binding
- `ctrl-api-resources` - Transform responses
- `ctrl-invokable` - Single action controllers
- `controller-single-action` - Single action invokable controllers
- `controller-resource-methods` - RESTful resource methods
- `controller-form-requests` - Use form requests
- `controller-api-resources` - Transform API responses
- `controller-middleware` - Apply middleware properly
- `controller-dependency-injection` - Inject dependencies
### 4. Validation & Requests (HIGH)
- `valid-form-requests` - Use form request classes
- `valid-custom-rules` - Create custom rules
- `valid-authorization` - Authorize in form requests
- `valid-messages` - Custom error messages
- `valid-conditional` - Conditional validation
- `validation-form-requests` - Use form request classes
- `validation-custom-rules` - Create custom rules
- `validation-conditional-rules` - Conditional validation
- `validation-array-validation` - Validate nested arrays
- `validation-after-hooks` - Complex validation logic
### 5. Security (HIGH)
- `sec-mass-assignment` - Protect against mass assignment
- `sec-sql-injection` - Prevent SQL injection
- `sec-xss` - Prevent XSS attacks
- `sec-csrf` - CSRF protection
- `sec-authentication` - Auth best practices
- `sec-authorization` - Policies and gates
- Additional security rules can be added as needed
### 6. Performance (MEDIUM)
- `perf-caching` - Cache strategies
- `perf-queues` - Queue heavy operations
- `perf-lazy-collections` - Memory efficient processing
- `perf-database-optimization` - Query optimization
- `perf-config-cache` - Cache configuration
- Performance rules can be added for caching, queues, and optimization
### 7. API Design (MEDIUM)
- `api-versioning` - API versioning strategy
- `api-resources` - API resource transformers
- `api-pagination` - Paginate responses
- `api-error-handling` - Consistent error responses
- `api-rate-limiting` - Rate limiting
### 8. Testing (LOW-MEDIUM)
- `test-feature-tests` - Feature/integration tests
- `test-unit-tests` - Unit test patterns
- `test-factories` - Model factories
- `test-mocking` - Mock external services
- `test-database` - Database testing
- API design rules can be added for versioning and response formatting
## Essential Patterns
@@ -347,12 +338,18 @@ Read individual rule files for detailed explanations and code examples:
```
rules/arch-service-classes.md
rules/db-eager-loading.md
rules/valid-form-requests.md
rules/eloquent-eager-loading.md
rules/validation-form-requests.md
rules/_sections.md
```
Each rule file contains:
- YAML frontmatter with metadata (title, impact, tags)
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Laravel-specific context and references
- Laravel 12 and PHP 8.5 specific context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
@@ -0,0 +1,75 @@
{
"version": "1.0.0",
"organization": "Laravel Community",
"date": "January 2026",
"laravelVersion": "12.x",
"phpVersion": "8.5+",
"abstract": "Comprehensive Laravel 12 best practices guide designed for AI agents and LLMs. Contains 30+ rules across 7 categories, prioritized by impact from critical (architecture and database patterns) to incremental (performance optimization). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations using PHP 8.5 and Laravel 12 features, and specific impact metrics to guide automated refactoring and code generation. Focuses on modern Laravel patterns including typed properties, constructor property promotion, enums, and readonly properties.",
"references": [
"https://laravel.com",
"https://laravel.com/docs/12.x",
"https://laravel.com/docs/12.x/eloquent",
"https://laravel.com/docs/12.x/controllers",
"https://laravel.com/docs/12.x/validation",
"https://laravel.com/docs/12.x/eloquent-relationships",
"https://laravel.com/docs/12.x/queries",
"https://laravel.com/docs/12.x/security",
"https://php.net/manual/en/language.types.declarations.php",
"https://github.com/laravel/laravel"
],
"categories": [
{
"name": "Architecture & Structure",
"prefix": "arch",
"impact": "CRITICAL",
"description": "Foundational patterns for organizing Laravel applications"
},
{
"name": "Eloquent & Database",
"prefix": "eloquent",
"impact": "CRITICAL",
"description": "Efficient database operations and ORM usage"
},
{
"name": "Controllers & Routing",
"prefix": "controller, ctrl",
"impact": "HIGH",
"description": "RESTful conventions and proper request handling"
},
{
"name": "Validation & Requests",
"prefix": "validation, valid",
"impact": "HIGH",
"description": "Form request classes and validation patterns"
},
{
"name": "Security",
"prefix": "sec",
"impact": "HIGH",
"description": "Protection against common vulnerabilities"
},
{
"name": "Performance",
"prefix": "perf",
"impact": "MEDIUM",
"description": "Caching strategies and optimization techniques"
},
{
"name": "API Design",
"prefix": "api",
"impact": "MEDIUM",
"description": "RESTful API patterns and resource transformers"
}
],
"keyFeatures": [
"Service classes for business logic separation",
"Eager loading to prevent N+1 queries",
"Form request classes for validation",
"Resource controllers following REST conventions",
"Eloquent relationships and query scopes",
"Mass assignment protection",
"API resources for response transformation",
"Modern PHP 8.5 syntax (readonly properties, constructor promotion)",
"Laravel 12 patterns and conventions"
]
}
@@ -1,36 +1,41 @@
# Rule Sections
# Sections
## Priority Levels
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
| Level | Description | When to Apply |
|-------|-------------|---------------|
| CRITICAL | Essential for any Laravel app | Always |
| HIGH | Important for maintainability | Most projects |
| MEDIUM | Performance and scalability | Growing applications |
| LOW | Specialized patterns | Large-scale apps |
---
## Section Overview
## 1. Architecture & Structure (arch)
### Architecture & Structure (CRITICAL)
Foundational patterns for organizing Laravel applications. Service classes, actions, and proper separation of concerns.
**Impact:** CRITICAL
**Description:** Foundational patterns for organizing Laravel applications. Service classes, action classes, DTOs, and proper separation of concerns are essential for maintainable, scalable codebases. These patterns determine long-term code quality and team productivity.
### Eloquent & Database (CRITICAL)
Patterns for efficient database operations. Preventing N+1 queries, proper indexing, and query optimization.
## 2. Eloquent & Database (eloquent)
### Controllers & Routing (HIGH)
RESTful conventions, resource controllers, and proper request handling.
**Impact:** CRITICAL
**Description:** Efficient database operations and ORM usage. Preventing N+1 queries through eager loading, using chunking for large datasets, and proper relationship management are critical for performance. Poor database patterns can cripple application performance at scale.
### Validation & Requests (HIGH)
Form request classes, custom validation rules, and authorization patterns.
## 3. Controllers & Routing (controller, ctrl)
### Security (HIGH)
Protection against common vulnerabilities and authentication/authorization best practices.
**Impact:** HIGH
**Description:** RESTful conventions, resource controllers, and proper request handling. Well-structured controllers following Laravel conventions improve code predictability, maintainability, and team collaboration. Thin controllers delegate to services for business logic.
### Performance (MEDIUM)
Caching strategies, queue usage, and optimization techniques.
## 4. Validation & Requests (validation, valid)
### API Design (MEDIUM)
RESTful API patterns, resource transformers, and consistent responses.
**Impact:** HIGH
**Description:** Form request classes, custom validation rules, and authorization patterns. Proper validation ensures data integrity, security, and separation of concerns. Centralized validation logic in form requests keeps controllers clean and validation rules reusable.
### Testing (LOW-MEDIUM)
Testing strategies, factories, and mocking patterns.
## 5. Security (sec)
**Impact:** HIGH
**Description:** Protection against common vulnerabilities including mass assignment, SQL injection, XSS, and CSRF attacks. Laravel provides excellent security features, but developers must use them correctly. Security issues can have catastrophic consequences.
## 6. Performance (perf)
**Impact:** MEDIUM
**Description:** Caching strategies, queue usage, and optimization techniques for growing applications. While not critical initially, performance patterns become essential as applications scale. Proper caching and queue usage can provide 2-10× improvements.
## 7. API Design (api)
**Impact:** MEDIUM
**Description:** RESTful API patterns, resource transformers, versioning, and consistent response formatting. Well-designed APIs are essential for frontend-backend communication, third-party integrations, and mobile applications. API resources provide consistent data transformation.
@@ -0,0 +1,67 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact (e.g., "2-5× performance improvement")
tags: tag1, tag2, tag3
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters in Laravel 12 applications. This should be clear and concise, explaining the performance, maintainability, or security implications. Focus on Laravel-specific context and patterns.
**Incorrect (description of what's wrong):**
```php
<?php
// Bad code example here
// Shows the antipattern or incorrect approach
class BadExample
{
public function badMethod()
{
// This demonstrates what NOT to do
}
}
```
**Correct (description of what's right):**
```php
<?php
// Good code example here
// Shows the recommended Laravel 12 pattern
class GoodExample
{
public function __construct(
private readonly DependencyService $service,
) {}
public function goodMethod(): ReturnType
{
// This demonstrates the correct approach
// Using modern PHP 8.5 and Laravel 12 features
}
}
```
**Additional context or variations (optional):**
```php
<?php
// Alternative patterns or edge cases
// Advanced usage examples
// Laravel 12 specific features
```
## Why It Matters
- **Benefit 1**: Specific advantage
- **Benefit 2**: Performance/security/maintainability improvement
- **Benefit 3**: How it helps in real-world Laravel applications
Reference: [Laravel 12 Documentation](https://laravel.com/docs/12.x)
@@ -1,4 +1,13 @@
# Action Classes
---
title: Single-Purpose Action Classes
impact: HIGH
impactDescription: Improves reusability and testability
tags: architecture, actions, single-responsibility, testability
---
## Single-Purpose Action Classes
**Impact: HIGH (Improves reusability and testability)**
Use single-purpose action classes for discrete operations to achieve maximum reusability and testability.
@@ -1,4 +1,13 @@
# Data Transfer Objects (DTOs)
---
title: Data Transfer Objects (DTOs)
impact: MEDIUM
impactDescription: Type safety and validation between layers
tags: architecture, dto, type-safety, validation
---
## Data Transfer Objects (DTOs)
**Impact: MEDIUM (Type safety and validation between layers)**
Use DTOs to transfer data between layers with type safety and validation.
@@ -1,4 +1,13 @@
# Event-Driven Architecture
---
title: Event-Driven Architecture
impact: HIGH
impactDescription: Decouples components and enables async processing
tags: architecture, events, listeners, decoupling, async
---
## Event-Driven Architecture
**Impact: HIGH (Decouples components and enables async processing)**
Use events and listeners to decouple components and handle side effects asynchronously.
@@ -1,4 +1,13 @@
# Feature Folders (Domain-Driven Structure)
---
title: Feature Folders (Domain-Driven Structure)
impact: MEDIUM
impactDescription: Better cohesion and discoverability
tags: architecture, organization, domain-driven, structure
---
## Feature Folders (Domain-Driven Structure)
**Impact: MEDIUM (Better cohesion and discoverability)**
Organize code by feature/domain rather than by type for better cohesion and discoverability.
@@ -1,4 +1,13 @@
# Repository Pattern
---
title: Repository Pattern
impact: MEDIUM
impactDescription: Abstracts data access from business logic
tags: architecture, repository, data-access, abstraction
---
## Repository Pattern
**Impact: MEDIUM (Abstracts data access from business logic)**
Abstract database queries into repository classes to decouple business logic from data access.
@@ -1,7 +1,13 @@
# arch-service-classes
---
title: Service Classes for Business Logic
impact: CRITICAL
impactDescription: Improves maintainability, testability, and code reusability
tags: architecture, services, separation-of-concerns, business-logic
---
**Priority:** CRITICAL
**Category:** Architecture & Structure
## Service Classes for Business Logic
**Impact: CRITICAL (Improves maintainability, testability, and code reusability)**
## Why It Matters
@@ -1,4 +1,13 @@
# Value Objects
---
title: Value Objects
impact: MEDIUM
impactDescription: Enforces business rules and improves type safety
tags: architecture, value-objects, domain-driven, type-safety
---
## Value Objects
**Impact: MEDIUM (Enforces business rules and improves type safety)**
Encapsulate domain concepts with value objects to enforce business rules and improve type safety.
@@ -1,4 +1,13 @@
# API Resources
---
title: API Resources for Response Transformation
impact: HIGH
impactDescription: Consistent API responses and data transformation
tags: controllers, api, resources, transformation
---
## API Resources for Response Transformation
**Impact: HIGH (Consistent API responses and data transformation)**
Use API Resources to transform models into consistent JSON responses.

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