ai-coding-principles

Principles and patterns for AI coding agents to write production-quality code. Use when generating code, modifying existing codebases, implementing features, fixing bugs, or when asked about "writing better code", "code quality", "best practices", or "production-ready code".

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "ai-coding-principles" with this command: npx skills add tawanorg/skills/tawanorg-skills-ai-coding-principles

AI Coding Principles

Actionable principles for AI coding agents to write production-quality code.

Golden Rules

These four rules apply to every coding task:

1. Read Before Writing

Always explore the codebase before generating code.

  • Search for similar implementations first
  • Understand existing patterns and conventions
  • Check how errors are handled elsewhere
  • Look at test patterns already in use
WRONG: Immediately generating a new utility function
RIGHT: Searching for existing utilities, then extending or reusing

2. Minimal Change Principle

Make the smallest change that solves the problem.

  • One bug fix = one focused change
  • Don't refactor unrelated code
  • Don't add features not requested
  • Don't "improve" working code opportunistically
WRONG: Fixing a typo and also reformatting the file
RIGHT: Fixing only the typo

3. Match the Codebase

Consistency over personal preference.

If the codebase uses...Use that, not...
snake_casecamelCase
TabsSpaces
Single quotesDouble quotes
Class componentsFunctional components
CallbacksPromises

Even if you "know better," match existing patterns unless explicitly asked to migrate.

4. Verify Understanding

Ask when uncertain. Assumptions cause rework.

Ask before proceeding when:

  • Requirements are ambiguous
  • Multiple valid approaches exist
  • Change might break existing functionality
  • You're unsure about business logic

Don't ask when:

  • Implementation is straightforward
  • You can verify with tests
  • The choice is purely stylistic

Error Handling

See references/error-handling-patterns.md for language-specific examples.

Principles

  1. Explicit over silent - Never swallow errors without logging
  2. Context is required - Include what failed, where, and why
  3. Fail fast in dev - Crash early to surface bugs
  4. Graceful in prod - Degrade functionality, don't crash users

Good vs Bad

// BAD: Silent failure, no context
try {
  await saveUser(data);
} catch (e) {
  return null;
}

// GOOD: Explicit handling with context
try {
  await saveUser(data);
} catch (error) {
  logger.error('Failed to save user', {
    userId: data.id,
    error: error.message,
    stack: error.stack,
  });
  throw new UserSaveError(`Could not save user ${data.id}`, { cause: error });
}

Error Handling Checklist

  • Are all errors logged with context?
  • Do error messages help debugging?
  • Are expected errors handled differently from unexpected?
  • Is sensitive data excluded from error messages?

Security Fundamentals

See references/security-checklist.md for the full checklist.

Non-Negotiable Rules

  1. Validate all external input - User input, API responses, file contents
  2. Use parameterized queries - Never concatenate SQL
  3. Manage secrets properly - Environment variables, never in code
  4. Never log sensitive data - Passwords, tokens, PII

Quick Security Check

Before completing any task:

[ ] User input is validated and sanitized
[ ] No secrets in code or logs
[ ] SQL uses parameterized queries
[ ] File paths are validated (no path traversal)
[ ] External data is treated as untrusted

Common Vulnerabilities to Avoid

VulnerabilityPrevention
SQL InjectionParameterized queries
XSSOutput encoding, CSP
Path TraversalValidate file paths
Command InjectionAvoid shell commands, use APIs
Secret ExposureEnvironment variables, secret managers

Testing Philosophy

See references/testing-patterns.md for implementation patterns.

What to Test

Critical paths:

  • User authentication flows
  • Payment/transaction logic
  • Data persistence operations
  • Core business rules

Edge cases:

  • Empty inputs
  • Boundary values
  • Error conditions
  • Concurrent operations

What Not to Over-Test

  • Trivial getters/setters
  • Framework code
  • Third-party libraries
  • Pure UI styling

Test Placement

Test TypeWhen to Use
Unit testsPure functions, isolated logic
Integration testsAPI endpoints, database operations
E2E testsCritical user journeys only

Testing Checklist

  • Are critical paths covered?
  • Do tests verify behavior, not implementation?
  • Are tests independent and repeatable?
  • Do tests have meaningful names?

Performance Considerations

Profile First

Never optimize without evidence. The bottleneck is rarely where you think.

  1. Measure current performance
  2. Identify actual bottleneck
  3. Fix the bottleneck
  4. Measure again

Common Pitfalls

PitfallSolution
N+1 queriesBatch fetching, eager loading
Memory leaksClean up listeners, close connections
Blocking I/OAsync operations
Repeated computationCaching, memoization
Large payloadsPagination, compression

Performance Checklist

  • Database queries are batched where possible
  • Large lists are paginated
  • Resources are properly cleaned up
  • Heavy computations are cached if repeated

Communication Patterns

When to Ask vs Proceed

Ask when:

  • Multiple valid implementations exist
  • Requirements seem incomplete
  • Change impacts other systems
  • Business logic is unclear

Proceed when:

  • Implementation is obvious
  • Tests can validate correctness
  • Change is isolated and reversible
  • Following existing patterns

Explaining Changes

When describing what you did:

  1. What - The specific change made
  2. Why - The reason for this approach
  3. Impact - What else might be affected
  4. Testing - How to verify it works
WRONG: "Fixed the bug"
RIGHT: "Fixed null pointer in UserService.getProfile() by adding
       null check before accessing user.settings. This was
       triggered when users hadn't completed onboarding."

Enterprise Patterns

The following sections cover enterprise-grade patterns essential for production systems.

Architecture & SOLID

See references/architecture-patterns.md for detailed examples.

SOLID Quick Reference

PrincipleRuleViolation Sign
Single ResponsibilityOne reason to changeClass doing validation, persistence, and notifications
Open/ClosedExtend, don't modifyAdding else if branches for new types
Liskov SubstitutionSubtypes are substitutableSubclass throws "not implemented"
Interface SegregationSmall, focused interfacesImplementing methods that throw
Dependency InversionDepend on abstractionsnew ConcreteClass() inside business logic

Layer Placement

If you're writing...It belongs in...
Business rulesDomain layer
Use case orchestrationApplication layer
Database queriesInfrastructure layer
HTTP handlingPresentation layer

Observability

See references/observability-patterns.md for implementation patterns.

The Three Pillars

PillarPurposeQuestion Answered
LogsDiscrete eventsWhat happened?
MetricsAggregated measurementsHow is it performing?
TracesRequest flowWhere did time go?

Logging Rules

  1. Structured JSON - Not string concatenation
  2. Request ID - Propagate through all logs
  3. Context - Include who, what, where, when
  4. Levels - error (failures), warn (degraded), info (business events), debug (diagnostics)

Four Golden Signals

Monitor these for every service:

  • Latency - Request duration
  • Traffic - Request rate
  • Errors - Failure rate
  • Saturation - Resource utilization

API Design

See references/api-design-patterns.md for conventions and examples.

REST Conventions

GET    /resources          List
POST   /resources          Create
GET    /resources/{id}     Read
PUT    /resources/{id}     Replace
PATCH  /resources/{id}     Update
DELETE /resources/{id}     Delete

Response Format

// Success
{ "data": {...}, "meta": { "requestId": "..." } }

// Error
{ "error": { "code": "USER_NOT_FOUND", "message": "...", "requestId": "..." } }

API Checklist

  • Correct HTTP methods and status codes
  • Request validation with clear errors
  • Consistent error format with codes
  • Pagination for collections
  • Versioning strategy defined

Database Patterns

See references/database-patterns.md for schema design and optimization.

Schema Essentials

-- Every table needs
id            -- Primary key (UUID preferred)
created_at    -- When created
updated_at    -- When modified
-- Optional
deleted_at    -- Soft delete

Query Rules

DoDon't
Select specific columnsSELECT *
Batch related queriesN+1 queries in loops
Use cursor paginationOffset at scale
Index foreign keysForget WHERE clause indexes
Parameterized queriesString concatenation

Resilience Patterns

See references/resilience-patterns.md for implementation details.

Everything Fails. Design for It.

PatternPurposeWhen to Use
RetryHandle transient failuresNetwork timeouts, 503s
Circuit BreakerStop cascading failuresRepeated downstream failures
TimeoutPrevent hangingEvery external call
BulkheadIsolate failuresCritical vs non-critical paths
FallbackGraceful degradationNon-critical features

Retry Guidelines

Retry: 503, 504, timeouts, connection errors
Don't retry: 400, 401, 403, 404, 422
Backoff: Exponential with jitter
Max attempts: 3-5 for most cases

Code Review

See references/code-review-checklist.md for the complete checklist.

Review Focus Areas

  1. Correctness - Does it work? Edge cases?
  2. Design - Right place? Right abstraction?
  3. Readability - Can you understand it?
  4. Security - Input validated? Auth checked?
  5. Testing - Critical paths covered?

Before Submitting (Self-Review)

  • I've tested this locally
  • I've reviewed my own diff
  • No debugging code left in
  • PR description explains what and why

Refactoring

See references/refactoring-patterns.md for safe refactoring techniques.

The Golden Rule

Make the change easy, then make the easy change.

When to Refactor

Refactor WhenDon't Refactor When
Adding features is hardNo tests exist
Same bug keeps appearingDon't understand the code
Code is hard to testTight deadline
You have test coveragePart of unrelated change

Safe Refactoring Process

  1. Verify test coverage exists
  2. Small incremental changes - commit frequently
  3. Keep behavior unchanged - tests should pass
  4. Separate from features - refactor PRs are pure refactoring

Quick Reference Checklist

Run through before completing any task:

Pre-Change

  • Read existing code in the area
  • Understand current patterns
  • Clarify ambiguous requirements

During Change

  • Minimal necessary changes
  • Match codebase style
  • Handle errors explicitly
  • Validate external input
  • No secrets in code

Post-Change

  • Tests pass
  • No regressions introduced
  • Changes are explained clearly

Principles Summary

Core Principles

PrincipleWhat It MeansAnti-Pattern
Read Before WriteExplore similar code firstGenerating code immediately
Minimal ChangeSmallest fix possibleRewriting file for typo
Match CodebaseFollow existing patternsUsing camelCase in snake_case project
Explicit ErrorsNever swallow silentlycatch (e) { return null }
Security DefaultValidate all external inputTrusting user data
Test Critical PathsFocus on what matters100% coverage goal
Profile FirstMeasure before optimizingPremature optimization
Ask When UncertainClarify before codingAssuming requirements

Enterprise Principles

PrincipleWhat It MeansAnti-Pattern
SOLID ArchitectureSingle responsibility, depend on abstractionsGod classes, tight coupling
Observable SystemsStructured logs, metrics, tracesconsole.log("here")
API ConsistencyStandard conventions, clear errorsRandom status codes, unstructured errors
Database DisciplineIndexes, parameterized queries, migrationsN+1 queries, string concatenation
Design for FailureTimeouts, retries, circuit breakersAssuming dependencies are reliable
Review Before MergeSystematic code reviewLGTM without reading
Refactor SafelyTests first, small changes, separate PRsBig bang rewrites

Reference Files

Comprehensive guides for deep understanding:

TopicFileUse When
Error Handlingreferences/error-handling-patterns.mdImplementing error handling
Securityreferences/security-checklist.mdSecurity review, input handling
Testingreferences/testing-patterns.mdWriting tests
Architecturereferences/architecture-patterns.mdDesigning components, applying SOLID
Observabilityreferences/observability-patterns.mdAdding logging, metrics, tracing
API Designreferences/api-design-patterns.mdBuilding REST APIs
Databasereferences/database-patterns.mdSchema design, query optimization
Resiliencereferences/resilience-patterns.mdHandling failures, external calls
Code Reviewreferences/code-review-checklist.mdReviewing code
Refactoringreferences/refactoring-patterns.mdImproving existing code

Rules

Atomic, enforceable rules for code review. Each rule follows: Incorrect → Correct → Why.

Security (CRITICAL)

RuleFile
Always Use Parameterized Queriesrules/security-parameterize-queries.md
Validate All External Inputrules/security-validate-input.md
Never Hardcode Secretsrules/security-no-secrets-in-code.md
Never Log Sensitive Datarules/security-no-sensitive-logs.md

Error Handling (HIGH)

RuleFile
Never Swallow Errors Silentlyrules/error-never-swallow.md
Include Context in Error Messagesrules/error-include-context.md

Database (HIGH)

RuleFile
Never Use SELECT *rules/db-no-select-star.md
Prevent N+1 Query Problemsrules/db-prevent-n-plus-one.md
Always Index Foreign Keysrules/db-index-foreign-keys.md

API Design (HIGH)

RuleFile
Use Correct HTTP Status Codesrules/api-correct-status-codes.md
Use Consistent Error Formatrules/api-consistent-errors.md
Validate All Request Bodiesrules/api-validate-requests.md

Architecture (HIGH)

RuleFile
Single Responsibility Principlerules/arch-single-responsibility.md
Depend on Abstractionsrules/arch-depend-on-abstractions.md

Testing (MEDIUM)

RuleFile
Test Behavior, Not Implementationrules/test-behavior-not-implementation.md
Prioritize Critical Pathsrules/test-critical-paths.md

Observability (MEDIUM)

RuleFile
Use Structured Loggingrules/obs-structured-logging.md
Include Request ID in All Logsrules/obs-include-request-id.md

Resilience (MEDIUM)

RuleFile
Always Set Timeoutsrules/resilience-always-timeout.md
Only Retry Transient Failuresrules/resilience-retry-transient.md

Refactoring (MEDIUM)

RuleFile
Have Tests Before Refactoringrules/refactor-tests-first.md
Make Small, Incremental Commitsrules/refactor-small-commits.md

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

system-design-thinking

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

Self Updater

⭐ OPEN SOURCE! GitHub: github.com/GhostDragon124/openclaw-self-updater ⭐ ONLY skill with Cron-aware + Idle detection! Auto-updates OpenClaw core & skills, an...

Registry SourceRecently Updated
1171Profile unavailable
Coding

ClawHub CLI Assistant

Use the ClawHub CLI to publish, inspect, version, update, sync, and troubleshoot OpenClaw skills from the terminal.

Registry SourceRecently Updated
1.9K2Profile unavailable
Coding

SkillTree Learning Progress Tracker

Track learning across topics like an RPG skill tree. Prerequisites, milestones, suggested next steps. Gamified learning path.

Registry SourceRecently Updated
900Profile unavailable