production-code-standards
Production-ready code standards following CLAUDE Framework with TDD, security, and quality requirements
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install primadetaautomation-primadata-marketplace-production-code-standards
Repository
Skill path: .claude/skills/production-code-standards
Production-ready code standards following CLAUDE Framework with TDD, security, and quality requirements
Open repositoryBest for
Primary workflow: Run DevOps.
Technical facets: Full Stack, Security.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: Primadetaautomation.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install production-code-standards into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/Primadetaautomation/primadata-marketplace before adding production-code-standards to shared team environments
- Use production-code-standards for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: production-code-standards
description: Production-ready code standards following CLAUDE Framework with TDD, security, and quality requirements
triggers: [production, code quality, standards, TDD, best practices, code review, maintainable, SOLID]
version: 1.0.0
agents: [senior-fullstack-developer, code-refactoring-specialist, qa-testing-engineer]
context_levels:
minimal: Core standards and quick reference
detailed: Complete patterns and examples
full: Scripts, templates, and automation tools
---
# Production Code Standards Skill
## Overview
This skill encapsulates the CLAUDE Framework standards for production-ready code development. It ensures consistency, quality, security, and maintainability across all code deliverables.
## When to Use This Skill
- Creating new features requiring production quality
- Code reviews against production standards
- Refactoring legacy code to modern standards
- Training on development best practices
- Pre-deployment quality validation
## Core Principles (Level 1 - Always Loaded)
### π― Priority Rules (CRITICAL - Non-Negotiable)
**Basis Missie - Breaking these = delivery rejected:**
- **BM-1 (MUST)**: Never invent, omit, or skip functionality
- **BM-2 (MUST)**: Follow exact instructions from user
- **BM-3 (MUST)**: Ask questions when unclear, never assume
**Impact Analysis - Before ANY code change:**
- **IA-1 (MUST)**: Analyze impact on existing functionality
- **IA-2 (MUST)**: Check all dependencies that will be affected
- **IA-3 (MUST)**: Search for all files that import/use the code
- **IA-4 (MUST)**: Run existing tests BEFORE changes
- **IA-5 (MUST)**: Backup/document original implementation when overwriting
- **IA-6 (MUST NOT)**: Never overwrite code without impact check
- **IA-7 (MUST)**: Ask permission before overwriting with impact explanation
### π΄ Code Quality Standards
**Single Responsibility & DRY:**
```typescript
// β
GOOD - Single responsibility
class UserAuthenticator {
authenticate(credentials: Credentials): AuthResult {
return this.validateAndAuthenticate(credentials);
}
}
class UserNotifier {
sendWelcomeEmail(user: User): void {
this.emailService.send(user.email, 'Welcome!');
}
}
// β BAD - Multiple responsibilities
class UserManager {
authenticate() { /* auth logic */ }
sendEmail() { /* email logic */ }
updateDatabase() { /* db logic */ }
}
```
**Naming Conventions (MUST):**
- Functions: `getUserData()`, `calculateTotal()` (verbs)
- Variables: `user`, `totalAmount` (nouns)
- Booleans: `isValid`, `hasPermission` (is/has prefix)
- Constants: `MAX_RETRY_COUNT`, `API_BASE_URL`
- Classes: `UserService`, `OrderController` (PascalCase)
**Function Size Limit:**
- Maximum 20 lines per function
- Extract complex logic into helper functions
- One level of abstraction per function
### π Error Handling (CRITICAL)
```typescript
// β
GOOD - Comprehensive error handling
async function fetchUserData(userId: string): Promise<User> {
try {
if (!userId || userId.trim() === '') {
throw new ValidationError('User ID is required');
}
const user = await db.users.findById(userId);
if (!user) {
throw new NotFoundError(`User ${userId} not found`);
}
logger.info('User fetched successfully', { userId });
return user;
} catch (error) {
if (error instanceof ValidationError || error instanceof NotFoundError) {
throw error;
}
logger.error('Failed to fetch user', { userId, error: error.message });
throw new DatabaseError('Failed to fetch user data');
}
}
// β BAD - Silent failure
async function fetchUserData(userId: string) {
try {
return await db.users.findById(userId);
} catch (error) {
return null; // Silent failure - NEVER do this!
}
}
```
**Error Handling Rules (MUST):**
- Handle all error scenarios explicitly
- Use specific error types/messages
- Log errors with context
- Never silent failures
- Fail fast: validate inputs early
### π§ͺ TDD Requirements (MUST)
**Red-Green-Refactor Cycle:**
1. **Red**: Write failing test first
2. **Green**: Write minimal code to pass
3. **Refactor**: Improve code quality
**Test Coverage Requirements:**
- Minimum 80% coverage for new code
- Test happy path, errors, edge cases
- Arrange-Act-Assert pattern
- Descriptive test names
```typescript
// β
GOOD - Descriptive test with AAA pattern
describe('UserAuthenticator', () => {
it('should return success when valid credentials provided', () => {
// Arrange
const authenticator = new UserAuthenticator();
const validCredentials = { email: '[email protected]', password: 'Valid123!' };
// Act
const result = authenticator.authenticate(validCredentials);
// Assert
expect(result.success).toBe(true);
expect(result.user).toBeDefined();
});
it('should throw ValidationError when email is missing', () => {
// Arrange
const authenticator = new UserAuthenticator();
const invalidCredentials = { email: '', password: 'Valid123!' };
// Act & Assert
expect(() => authenticator.authenticate(invalidCredentials))
.toThrow(ValidationError);
});
});
```
### π Security Rules (CRITICAL)
**Input Validation (MUST):**
```typescript
// β
GOOD - Validate at boundaries
function createUser(input: unknown): User {
const validated = userSchema.parse(input); // Zod/Joi validation
// Sanitize
const sanitized = {
email: validator.normalizeEmail(validated.email),
name: validator.escape(validated.name),
};
return userService.create(sanitized);
}
// β BAD - No validation
function createUser(input: any) {
return userService.create(input); // Unsafe!
}
```
**Security Requirements (MUST):**
- Input validation at system boundaries
- Output sanitization
- Secrets via env vars/vault (never hardcoded)
- Never log sensitive data (passwords, tokens, PII)
- TLS everywhere, HSTS, secure cookies
- Dependency scanning enabled
## Detailed Patterns (Level 2 - Load on Request)
See companion files:
- `detailed-patterns.md` - Advanced patterns and examples
- `refactoring-guide.md` - Step-by-step refactoring strategies
- `security-checklist.md` - Comprehensive security validation
## Automation Tools (Level 3 - Load When Needed)
See scripts directory:
- `scripts/pre-commit-check.sh` - Run before commits
- `scripts/quality-gate.sh` - CI/CD quality validation
- `scripts/security-scan.sh` - Dependency and secret scanning
## Quick Reference Checklist
Before marking any task complete:
- [ ] All MUST rules followed
- [ ] Impact analysis completed
- [ ] Tests written first (TDD)
- [ ] 80%+ test coverage
- [ ] All error scenarios handled
- [ ] Security validation passed
- [ ] No hardcoded secrets
- [ ] Functions under 20 lines
- [ ] Descriptive naming used
- [ ] Code reviewed
## Integration with Agents
**senior-fullstack-developer:**
- Primary agent for implementing these standards
- Uses this skill for all production code
- References detailed patterns for complex scenarios
**code-refactoring-specialist:**
- Uses this skill when modernizing legacy code
- Applies standards during refactoring
- Validates against quality checklist
**qa-testing-engineer:**
- Uses this skill to validate test coverage
- Ensures TDD compliance
- Reviews test quality against standards
## Success Metrics
Track these KPIs:
- First-time success rate > 70%
- Average iterations < 3
- Test coverage > 80%
- Security issues: 0
- Production bugs < 2/week
---
*Version 1.0.0 | Compatible with CLAUDE Framework v5.0*
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### scripts/pre-commit-check.sh
```bash
#!/bin/bash
# Pre-commit Quality Gate
# Run this before committing code to ensure standards compliance
set -e
echo "π Running pre-commit quality checks..."
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Check if required tools are installed
check_tool() {
if ! command -v $1 &> /dev/null; then
echo -e "${YELLOW}β οΈ $1 not found, skipping $2${NC}"
return 1
fi
return 0
}
# Track failures
FAILED=0
# 1. Linting
echo "π Running linter..."
if check_tool "eslint" "linting"; then
if eslint . --ext .ts,.tsx,.js,.jsx; then
echo -e "${GREEN}β Linting passed${NC}"
else
echo -e "${RED}β Linting failed${NC}"
FAILED=1
fi
fi
# 2. Type checking
echo "π€ Running type checker..."
if check_tool "tsc" "type checking"; then
if tsc --noEmit; then
echo -e "${GREEN}β Type checking passed${NC}"
else
echo -e "${RED}β Type checking failed${NC}"
FAILED=1
fi
fi
# 3. Tests
echo "π§ͺ Running tests..."
if check_tool "npm" "tests"; then
if npm test -- --coverage --coverageThreshold='{"global":{"lines":80}}'; then
echo -e "${GREEN}β Tests passed with sufficient coverage${NC}"
else
echo -e "${RED}β Tests failed or coverage below 80%${NC}"
FAILED=1
fi
fi
# 4. Security scan
echo "π Scanning for vulnerabilities..."
if check_tool "npm" "security scan"; then
if npm audit --audit-level=high; then
echo -e "${GREEN}β No high/critical vulnerabilities${NC}"
else
echo -e "${YELLOW}β οΈ Vulnerabilities found, review npm audit output${NC}"
fi
fi
# 5. Check for hardcoded secrets
echo "π Checking for secrets..."
if check_tool "gitleaks" "secret scanning"; then
if gitleaks detect --no-git; then
echo -e "${GREEN}β No secrets detected${NC}"
else
echo -e "${RED}β Potential secrets found${NC}"
FAILED=1
fi
else
echo " Checking for common patterns manually..."
if grep -r -E "(password|secret|api[_-]?key|token)\s*=\s*['\"][^'\"]+['\"]" . --exclude-dir=node_modules --exclude-dir=.git 2>/dev/null; then
echo -e "${RED}β Possible hardcoded secrets found${NC}"
FAILED=1
else
echo -e "${GREEN}β No obvious secrets detected${NC}"
fi
fi
# 6. Check function length
echo "π Checking function length..."
LONG_FUNCTIONS=$(find . -name "*.ts" -o -name "*.js" | grep -v node_modules | xargs grep -E "^\s*(function|async function|const \w+ = \(.*\) =>)" -A 25 | grep -c "^--$" || true)
if [ "$LONG_FUNCTIONS" -gt 0 ]; then
echo -e "${YELLOW}β οΈ Found functions longer than 20 lines${NC}"
else
echo -e "${GREEN}β All functions within size limits${NC}"
fi
# Final result
echo ""
if [ $FAILED -eq 0 ]; then
echo -e "${GREEN}β
All quality checks passed!${NC}"
exit 0
else
echo -e "${RED}β Quality checks failed. Please fix issues before committing.${NC}"
exit 1
fi
```