clean-principles
v1.2.1
Published
Clean coding principles for AI agents: SOLID, Clean Code, DRY/KISS/YAGNI, Design Patterns, Architecture, Testing, and Clarify Before Build — language-agnostic, works with any AI coding agent.
Maintainers
Readme
🧼 clean-principles
Senior-level software engineering standards & architectural principles for AI coding agents.
💡 The Philosophy: Senior 10+ YoE Mindset
By default, AI coding agents write code that compiles, but is painful for humans to maintain: 800-line monolithic files, 6 levels of nested if/else staircases, cryptic abbreviations, and foreign paradigms (like writing Java in Python).
clean-principles injects an uncompromising 10+ Year Senior Engineer standard directly into the agent's subconscious reasoning layer:
"Write code for humans first, compiler second. Optimize for the tired on-call engineer debugging an outage at 2 AM."
Core Engineering Tenets
- The 300-Line Rule: Files must stay focused ($\le 300$ lines). A file exceeding 300 lines is a code smell signaling that it's time to decompose into cohesive modules.
- Flattened Control Flow (Anti-Arrow): Kill the Arrow Anti-Pattern. Always use Guard Clauses and exit early. The happy path stays at root indentation (max nesting level $\le 2$).
- Self-Documenting Code: Ban complex boolean soups and dense one-liners. Encapsulate business logic into intention-revealing predicates and named constants.
- Ecosystem & Idiom First: Never transplant alien paradigms. Adhere strictly to language idioms (PEP 8, PSR-12/Laravel, Effective Go, React Rules of Hooks, Rust API Guidelines) and respect local linter/formatter configurations.
⚡ Quick Install
1. Via Marketplace (Recommended)
| Agent Platform | Installation Command |
|---|---|
| Antigravity (AGY) | agy plugin install https://github.com/Khuirul-Huda/clean-principles |
| Claude Code | /plugin marketplace add Khuirul-Huda/clean-principles/plugin install clean-principles@clean-principles |
| Cursor / Windsurf | Add AGENTS.md to your project root or workspace instructions. |
| OpenAI Codex | codex plugin marketplace add Khuirul-Huda/clean-principlescodex plugin add clean-principles@clean-principles |
| GitHub Copilot CLI | copilot plugin marketplace add Khuirul-Huda/clean-principlescopilot plugin install clean-principles@clean-principles |
| npm / npx (Universal) | npx clean-principles |
2. Universal / Project Root Install (CLI)
Run directly with npx to install AGENTS.md, .cursor/rules/, and .agents/skills/ into your project root:
npx clean-principlesOr copy AGENTS.md manually via curl:
curl -sSL https://raw.githubusercontent.com/Khuirul-Huda/clean-principles/main/AGENTS.md -o AGENTS.md🛡️ Always-On Enforcement & Lifecycle Hooks
Unlike standard passive skills that sit dormant until explicitly invoked, clean-principles actively enforces quality gates on every user prompt and session:
- Ambiguity Gate (
clarify-before-build): If a prompt uses vague terms like "simple", "quick", "clean", or "production-ready", the agent halts unrequested expansion and asks 1 targeted clarifying question before writing code. - Lifecycle Hooks:
- Claude Code & Codex: Automatically runs
SessionStart(injecting full rules) andUserPromptSubmit(intercepting every prompt to detect domains and inject exact skill paths to read). - Antigravity (AGY): Registered via
gemini-extension.jsonandrules/core-principles.mdfor active session injection. - Cursor: Enforced globally across all workspaces via
.cursor/rules/clean-principles.mdc(alwaysApply: true).
- Claude Code & Codex: Automatically runs
- Mandatory Full-Skill Reading: When tasks enter specific domains (Testing, Architecture, Design Patterns, SOLID, Clean Code, DRY/YAGNI), the agent is instructed to read the full
SKILL.mdbefore coding. - Pre-Output Verification Gate: All generated functions are audited against the ≤ 3 parameter rule, Single Responsibility (SRP), file sizing limits, and no magic numbers before completion.
⚖️ Comparison: With vs. Without clean-principles
| Dimension | ❌ Without Plugin (Default AI Behavior) | ✅ With clean-principles |
|---|---|---|
| Class & File Sizing | 800-line monolithic "God Files" mixing database, UI, validation, and API calls. | Strict SRP & DIP. Target ≤ 300 lines/file; cleanly decomposed into cohesive single-purpose files. |
| Control Flow & Nesting | Deeply nested if/else staircases (Arrow Anti-Pattern, nesting 4–6 levels deep). | Guard Clauses: Exit early on invalid states. Flat structure, happy path at root indentation (nesting ≤ 2). |
| Language & Idioms | Writes "Java in Python" or procedural code in Laravel; ignores project linters. | Idiom-first & Toolchain-aware: Respects PEP 8, PSR-12, Effective Go, and reads tsconfig/phpstan configs first. |
| API & Method Design | Boolean flag arguments (process(true)), cryptic names (u_id, usrActFlg). | Expressive verb phrases (processStandard(), processPromotional()), intention-revealing names. |
| Ambiguous Prompts | Speculative code expansion; outputs 1,500+ tokens of hybrid guesswork. | Clarify before build: Asks 1 concise spectrum question (~120 tokens) before touching code. |
| Error Handling | Swallows errors (except: return None) or raises generic Exception. | Specific custom domain exceptions, fails fast, returns empty collections instead of null/None. |
| Over-Engineering | Generates premature factories and abstract bridges for simple 20-line scripts. | Pragmatic guardrails: explicit "When NOT to apply" rules (KISS > patterns for small scripts). |
| Testability | Tight coupling to external services; hard to test without heavy mocks. | Inverted dependencies allow blazing fast, in-memory unit testing. |
🔍 Code Transformation Example
```python
# ❌ BEFORE: Default Agent Code (Messy, nested, mixed concerns, boolean flags)
def handle_student(data, flag=False, retry=3):
if data:
if "id" in data and "courses" in data:
if flag == True:
# Magic numbers, deeply nested validation
if data["gpa"] >= 3.5 and data["income"] < 50000:
for c in data["courses"]:
if check_capacity(c) == True:
db.query(f"INSERT INTO enrollments VALUES ({data['id']}, {c})")
send_email(data["email"], "Enrolled in " + str(c))
else:
return None
else:
pass
return True
```
<!-- slide -->
```python
# ✅ AFTER: With clean-principles (Flat guard clauses, typed, SRP, ≤ 3 params)
MIN_GPA_THRESHOLD = 3.5
MAX_FAMILY_INCOME = 50_000
def is_eligible(student: Student) -> bool:
if student is None or student.has_disciplinary_record:
return False
return student.gpa >= MIN_GPA_THRESHOLD and student.income < MAX_FAMILY_INCOME
class EnrollmentService:
def __init__(self, db: Database, mailer: Mailer):
self._db = db
self._mailer = mailer
def enroll(self, student: Student, course: Course) -> bool:
if not course.has_capacity():
raise CourseCapacityExceededError(f"Course {course.id} is full.")
if not is_eligible(student):
return False
# Happy path at root indentation
self._persist_enrollment(student, course)
self._send_confirmation(student)
return True
```📦 What's Included
🛡️ Always-On Rules & Hooks (Loaded Every Turn)
rules/core-principles.md: Baseline standards for naming, function sizing, file line limits ($\le 300$ lines), guard clauses, error handling, full-skill read triggers, and pre-commit checklists.hooks/claude-codex-hooks.json:SessionStartandUserPromptSubmitlifecycle hooks with domain-aware skill injection.gemini-extension.json: Native Antigravity / Gemini CLI extension manifest..cursor/rules/clean-principles.mdc: Always-on Cursor rules withalwaysApply: true.AGENTS.md/CLAUDE.md: Standard cross-agent configurations recognized across all major agent frameworks.
🧠 7 Deep Principle Skills (Loaded Dynamically)
| Skill | Trigger / When to Apply | Focus Areas |
|---|---|---|
| clean-code | Naming, writing functions, refactoring messy code | 300-Line Rule, Guard Clauses, Senior 10+ YoE Standard, Ecosystem Idioms |
| solid-principles | Designing classes/modules, interfaces, coupling | SRP, OCP, LSP, ISP, Dependency Inversion (DIP) |
| dry-kiss-yagni | Seeing duplication, premature abstraction | Single Source of Truth, Simplest Solution, No "Just-in-Case" code |
| design-patterns | Recurring structural & behavioral challenges | Factory, Strategy, Observer, Repository, Facade, Template Method |
| architecture-principles | System boundaries, splitting packages | Layered, Hexagonal/Clean Architecture, High Cohesion, Loose Coupling |
| testing-principles | Writing tests, test design, brittle suites | TDD, FIRST, AAA Pattern, Test Doubles, Testing Pyramid |
| clarify-before-build | Ambiguous prompt keywords ("simple", "clean") | Multi-choice disambiguation before generating 1,000+ tokens of guesswork |
📂 Repository Structure
clean-principles/
├── plugin.json # Antigravity (AGY) plugin manifest
├── package.json # npm package manifest
├── gemini-extension.json # Antigravity / Gemini CLI extension manifest
├── AGENTS.md # Always-on rules for universal AI agents
├── CLAUDE.md # Claude Code entry point
├── hooks/ # Claude Code & Codex lifecycle hooks
├── .claude-plugin/ # Claude Code marketplace & plugin manifests
├── .agents/ # Antigravity & Codex marketplace manifests
├── .cursor/ # Cursor alwaysApply rules
├── .cursor-plugin/ # Cursor plugin manifest
├── .codex-plugin/ # OpenAI Codex plugin manifest
├── rules/
│ └── core-principles.md # Baseline always-on rules (300 lines, guard clauses)
└── skills/ # 7 comprehensive principle skills
├── clean-code/
├── solid-principles/
├── dry-kiss-yagni/
├── design-patterns/
├── architecture-principles/
├── testing-principles/
└── clarify-before-build/🤝 Contributing
Contributions, issues, and feature requests are welcome!
Skills follow standard AI agent skills specifications. Commit messages follow Conventional Commits (see CONTRIBUTING.md).
📄 License
This project is licensed under the MIT License.
