# clean-code-ai

Adopt this skill: https://proskills.md/skills/other/di0rio-cd-skills-skills-clean-code-ai

Page: https://proskills.md/skills/other/di0rio-cd-skills-skills-clean-code-ai
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/clean-code-ai/SKILL.md
size: 8006
upstream: https://github.com/di0rio/cd-skills/blob/main/skills/clean-code-ai/SKILL.md

````text
---
name: clean-code-ai
description: Keeps code simple, short and free of overengineering. Use whenever writing, fixing, refactoring or reviewing code: new feature, bugfix, refactor, code review, library choice, architecture, styling (CSS) or state. Delivers the smallest correct, safe solution that fits the project, in the narrowest scope that works (KISS, YAGNI, smallest correct change, root cause, contracts preserved). Also triggers on "simple", "minimal", "yagni", "no overengineering", "match the codebase", or when a new layer, an unnecessary dependency, global CSS/state "for reuse", a silenced lint or an empty catch shows up. Minimal means smallest correct, never least safe. Not for non-coding requests.
argument-hint: "[lite|full|ultra|off]"
---

# Clean Code AI

**Goal:** the smallest correct, safe solution that fits the project, in the narrowest scope that works and following the conventions that already exist. Not the most sophisticated code: the simplest that solves the current problem.

Act like a senior dev who has been woken up at 3am by overengineered code: the best code is the code that did not need to be written. Lazy here means efficient, not careless.

**Smaller never beats correct.** Understand the flow first, then be minimal. The smallest change in the wrong place is not simple, it is a second bug. Optimize for the smallest **correct** change, not the smallest textual diff.

## Activation and levels

Active on every code response until the user asks for `/clean-code-ai off`. Default is **full**. Switch with `/clean-code-ai lite|full|ultra`. The level holds until it is changed or the session ends.

- **lite:** does what was asked and mentions the simpler alternative in one line. The user chooses.
- **full:** applies the ladder below and the stop criterion. Smallest correct change, smallest explanation.
- **ultra:** extreme YAGNI. Removes before adding. Delivers the minimal version and questions the rest of the requirement in the same reply.

Example: "add a cache to these API responses".
- lite: "Cache added. Note: Next's `fetch` `revalidate` already covers this without a cache class."
- full: "`next: { revalidate: 3600 }` on the fetch. Skipped a custom cache class, add it when revalidate is not enough."
- ultra: "No cache until someone measures slowness. When they do: `revalidate` on the fetch. Hand-rolled cache is a bug factory."

At every level, "Where NOT to simplify" and "When minimal is wrong" apply in full.

This skill decides **what** to build, not **how** to speak. Tone and reply length are left to other instructions (e.g. caveman).

## Priority on conflict

1. Security (auth, authorization, validation at the trust boundary)
2. Functional correctness and explicit requirements
3. Existing contracts (exported functions, endpoints, schemas, props, database)
4. Data integrity
5. Project conventions
6. Simplicity
7. Readability
8. Performance, only with measured need
9. Personal taste in style and abstraction

Simplicity **never** justifies removing authentication, authorization, validation, integrity, error handling, accessibility basics or an explicit requirement.

## Before writing

Read the task and the code it touches. Trace the real flow end to end. Find who consumes what you are about to change (grep calls, imports, who uses the endpoint). Look for a helper, component, token or pattern that already exists. Only then choose the solution.

The ladder shortens the solution, never the reading. Skipping understanding to ship a small diff is the dangerous kind of laziness: it looks like efficiency and delivers a confidently wrong fix.

## Solution ladder

Stop at the first rung that solves it **correctly**:

1. Does this need to exist? Speculative need: skip it and say so in one line.
2. Remove code.
3. Reuse what already exists in the project.
4. Standard library / native API of the runtime or framework.
5. Native platform feature: HTML/CSS before JS (`<input type="date">` before a datepicker lib, `<details>` before a hand-made accordion), database constraint before application code.
6. Already-installed dependency (installed does not mean mandatory).
7. A few simple lines.
8. Abstraction, only when it removes real complexity, isolates a real external boundary (vendor, I/O, third-party service, a boundary the project already isolates) or has 2+ real uses today. "We might swap it someday" does not count.
9. New dependency, only if it saves a lot more than it costs.
10. New infrastructure, only if unavoidable.

If two rungs work: stay with the higher one and move on. Two options of the same size: stay with the one that gets the edge cases right. Simple means writing less code, not picking the most fragile algorithm.

## Scope and locality (minimal is not centralized)

Reusing does not mean global. Put each thing in the narrowest scope that works and follow how the project already does it.

- **Styling:** use the project's convention (Tailwind utilities, CSS Modules, styles next to the component). A value used once stays local. Promote to a token or global variable only when it is a shared design decision, used in 2+ places, and the project already has a token system. Do not create global CSS, a `:root` variable or a theme entry for a single use. Do not invent a token system that does not exist.
- **State:** stays in the component. Lift it only to the nearest common parent that needs it. Context, store, singleton or mutable module state only when the state is truly shared between distant parts.
- **Helpers and constants:** next to the single place that uses them. Move to `utils/` or `shared/` when the second real consumer appears.
- **Duplication:** copying twice is fine; a wrong abstraction is worse. Extract when the same rule shows up again and will evolve together.

```diff
- /* globals.css */
- :root { --contact-card-gap: 14px; }
- .contact-card { gap: var(--contact-card-gap); }
+ <div className="flex gap-3.5">   {/* one use, project uses Tailwind */}
```

## Bugs: root cause

The report describes a symptom. Before editing, grep everyone who calls the function you are about to touch. Trace to the origin and fix it once, at the point every caller goes through: a guard in the shared function is a smaller diff than a guard in each caller, and fixing only the path the ticket mentions leaves the others broken. Do not scatter guards to hide a broken contract.

## What to avoid (what AI gets wrong most)

- Interface, factory, strategy or adapter with a single implementation (except a real external boundary, see rung 8).
- Layers that only forward the call (`Controller -> Service -> Repository`) with no responsibility of their own. DI container and repository by default. A pattern is a tool, not a requirement.
- Code "for the future": options, flags, configs and scaffolding nobody asked for. The future does its own scaffolding.
- Config for a value that never changes.
- A new file when it fits in the existing one.
- A new package for something 5 lines solve.
- Global CSS, state or helper for a single use (see "Scope and locality").
- Empty `try/catch` or one that swallows unexpected errors.
- `any`, `as`, `@ts-ignore`, `eslint-disable` or `biome-ignore` just to quiet the compiler. Fix the type or narrow.
- Refactoring, renaming or reformatting code outside the scope.
- Comments that repeat the code.
- Temporary logs, commented-out code, trivial TODOs.
- A constant for every literal, a function for every line, a test for a trivial wrapper.
- Clever instead of obvious. Clever is what someone has to decipher at 3am.

## Examples

**Premature abstraction**

```ts
// ❌
interface PriceCalculator { calculate(items: Item[]): number }
class DefaultPriceCalculator implements PriceCalculator {
  calculate(items: Item[]) { return items.reduce((sum, item) => sum + item.price, 0) }
}
const calculator = PriceCalculatorFactory.create()

// ✅
const total = items.reduce((sum, item) => sum + item.price, 0)
```

**Unnecessary dependency**

```ts
// ❌
i
````

## File: README.md
upstream: https://github.com/di0rio/cd-skills/blob/main/README.md

````text
# clean-code-ai

A skill for AI coding agents (Claude Code, Codex, Cursor and others) that asks for **the smallest correct, safe and readable change that fits the project you are in**.

Minimal means smallest correct and narrowest scope. It never means least safe.

## Why

Coding agents overbuild: new layers, new dependencies, a global stylesheet for a one-off value, an `eslint-disable` to make the build pass. "Do less" rules fix part of that, but pushing hard for "shortest" brings its own failure modes:

- reuse turned into centralization (a `:root` variable or a store for something used once);
- code deleted because it looks unused, while it is wired by name from config;
- validation, error handling or a needed test dropped to save lines;
- clever one-liners that are shorter and harder to read.

`clean-code-ai` keeps the "do less" instinct and puts security, correctness and contracts above it.

## What is inside

[`SKILL.md`](SKILL.md), about 2,500 words. A Portuguese version of the same skill is in [`SKILL.pt.md`](SKILL.pt.md).

- **levels**: `lite`, `full` (default), `ultra` and `off`, switched with `/clean-code-ai lite|full|ultra|off`
- **priority order** on conflict: security, correctness, explicit requirements and contracts before simplicity
- **solution ladder**: does it need to exist, remove code, reuse, stdlib, native platform feature (HTML/CSS before JS, database constraint before app code), installed dependency, a few lines, abstraction only with 2+ real uses, then new dependency or infrastructure
- **scope and locality**: styling and state live in the narrowest scope that works; a global token only for a real shared design decision
- **root cause** first, instead of guards in every caller
- **errors, types and tools**: no empty `catch`, no silenced lint or types, generated files left to their generator
- **readability**: clear beats short, comment the why, a `// clean-code-ai:` comment for known limits
- a **frontend** section for React, Next.js and Tailwind
- **dependencies**, and **where not to simplify** (backend validation, database guarantees, idempotency, accessibility)
- **when minimal is wrong**: the cases where the right move is to do more
- **contracts** and breaking changes flagged before they are applied
- a **stop criterion**: past ~50 lines, a new file, abstraction, global or dependency means one sentence of justification, unless the user explicitly asked for the feature
- a **reply format** and a short final **checklist**

## Install

Claude Code, as a personal skill:

```bash
mkdir -p ~/.claude/skills/clean-code-ai
curl -fsSL https://raw.githubusercontent.com/di0rio/cd-skills/main/skills/clean-code-ai/SKILL.md -o ~/.claude/skills/clean-code-ai/SKILL.md
```

Portuguese version, same folder and file name:

```bash
curl -fsSL https://raw.githubusercontent.com/di0rio/cd-skills/main/skills/clean-code-ai/SKILL.pt.md -o ~/.claude/skills/clean-code-ai/SKILL.md
```

With the [skills CLI](https://skills.sh):

```bash
npx skills add di0rio/cd-skills --skill clean-code-ai
```

Any other agent: paste the body of `SKILL.md` into your rules file (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules`).

## How I tested it

I ran five small tasks (a styling change, a bug with several callers, a feature that tempts a new dependency, a "simplify this" handler with auth and validation, and dead-code cleanup) with no rules, with another "do less" skill, with the previous version of this skill (`pragmatic-code`) and with clean-code-ai, then had a separate model score all attempts blind.

Result, out of 200: clean-code-ai 191, pragmatic-code 190, no rules 176, the other skill 166. clean-code-ai and pragmatic-code are a tie within noise; the gain over no rules comes mostly from the dead-code and styling tasks. Details in [`bench/clean-code-ai/RESULTS.md`](../../bench/clean-code-ai/RESULTS.md).

It is a smoke test, not proof: one run per setup, an LLM judge, and tasks I wrote myself around the failure modes above. The tasks, raw outputs and verdict are in [`bench/clean-code-ai/`](../../bench/clean-code-ai/) so anyone can rerun or challenge them. Pull requests with new tasks are welcome, especially ones where the skill does worse.

## Background

`clean-code-ai` merges `pragmatic-code` with an earlier `clean-code-ai` draft of mine, and replaces `pragmatic-code`.

Thanks to [ponytail](https://ponytail.dev/), which shaped how this skill is written: short, with a clear trigger description and a fixed reply format. The story behind the skill and what I learned from it is in the post [a skill que escrevi pra IA parar de complicar meu código](https://cauadiorio.vercel.app/blog/skill-de-codigo-pragmatico) (Portuguese, with an English version on the same site).

## License

[MIT](../../LICENSE)
````
