Use when found gap or repetative issue, that produced by you or implemenataion agent. Esentially use it each time when you say "You absolutly right, I should have done it differently." -> need create rule for this issue so it not appears again.
48
36%
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Passed
No known issues
Optimize this skill with Tessl
npx tessl skill review --optimize ./plugins/customaize-agent/skills/create-rule/SKILL.mdGuide for creating effective .claude/rules files with contrastive examples that improve agent accuracy.
Core principle: Effective rules use contrastive examples (Incorrect vs Correct) to eliminate ambiguity.
REQUIRED BACKGROUND: Rules are behavioral guardrails, that load into every session and shapes how agents behave across all tasks. Skills load on-demand. If guidance is task-specific, create a skill instead.
Rules are modular, always-loaded instructions placed in .claude/rules/ that enforce consistent behavior. They act as "standing orders" — every agent session inherits them automatically.
| Aspect | Rules (.claude/rules/) | Skills (skills/) | CLAUDE.md |
|---|---|---|---|
| Loading | Every session (or path-scoped) | On-demand when triggered | Every session |
| Purpose | Behavioral constraints | Procedural knowledge | Project overview |
| Scope | Narrow, focused topics | Complete workflows | Broad project context |
| Size | Small (50-200 words each) | Medium (200-2000 words) | Medium (project summary) |
| Format | Contrastive examples | Step-by-step guides | Key-value / bullet points |
Create when:
Do NOT create for:
paths frontmatter)Load every session. Use for universal constraints.
# Error Handling
All error handlers must log the error before rethrowing.
Never silently swallow exceptions.paths frontmatter)Load only when agent works with matching files. Use for file-type-specific guidance.
---
paths:
- "src/api/**/*.ts"
---
# API Development Rules
All API endpoints must include input validation.
Use the standard error response format.Explicit high-level rules that set evaluation priorities.
# Evaluation Priorities
Prioritize correctness over style.
Do not reward hallucinated detail.
Penalize confident wrong answers more than uncertain correct ones.Every rule MUST follow the Description-Incorrect-Correct template. This structure eliminates ambiguity by showing both what NOT to do and what TO do.
---
title: Short Rule Name
paths: # Optional but preferable: when it is possible to define, use it!
- "src/**/*.ts"
---
# Rule Name
[1-2 sentence description of what the rule enforces and WHY it matters.]
## Incorrect
[Description of what is wrong with this pattern.]
\`\`\`language
// Anti-pattern code or behavior example
\`\`\`
## Correct
[Description of why this pattern is better.]
\`\`\`language
// Recommended code or behavior example
\`\`\`
## Reference
[Optional: links to documentation, papers, or related rules.]Researches shows that rules with both positive and negative examples are significantly more discriminative than rules with only positive guidance. The Incorrect/Correct pairing:
Explicit, high-level guidance:
| Principle | Example |
|---|---|
| Prioritize correctness over style | "A functionally correct but ugly solution is better than an elegant but broken one" |
| Do not reward hallucinated detail | "Extra information not grounded in the codebase should be penalized, not rewarded" |
| Penalize confident errors | "A confidently stated wrong answer is worse than an uncertain correct one" |
| Be specific, not vague | "Functions must not exceed 50 lines" not "Keep functions short" |
| State the WHY | "Use early returns to reduce nesting — deeply nested code increases cognitive load" |
The Incorrect section must show a pattern the agent would plausibly produce. Abstract or contrived bad examples provide no value.
Effective Incorrect examples:
Ineffective Incorrect examples:
The Correct section must show the minimal change needed to fix the Incorrect pattern. Large rewrites obscure the actual lesson.
Effective Correct examples:
Ineffective Correct examples:
Rules load every session. Every token counts.
.claude/
├── CLAUDE.md # Project overview (broad)
└── rules/
├── code-style.md # Global: code formatting rules
├── error-handling.md # Global: error handling patterns
├── testing.md # Global: testing conventions
├── security.md # Global: security requirements
├── evaluation-priorities.md # Global: judge/evaluator priorities
├── frontend/
│ ├── components.md # Path-scoped: React component rules
│ └── state-management.md # Path-scoped: state management rules
└── backend/
├── api-design.md # Path-scoped: API patterns
└── database.md # Path-scoped: database conventionsNaming conventions:
error-handling.md, not ErrorHandling.mderror-handling.md, not try-catch-patterns.mdFollow these steps in order, skipping only when a step is clearly not applicable.
Before writing any rule, identify the specific agent behavior that needs correction. This understanding can come from:
Document the gap as a concrete statement: "The agent does X, but should do Y."
Conclude this step when there is a clear, specific behavior to correct.
Decide whether this rule should be:
paths frontmatter) — applies to all work in the projectpaths frontmatter with glob patterns) — applies only when working with matching files~/.claude/rules/) — applies across all projects for personal preferencesDecision guide:
Is this project-specific?
No → User-level rule (~/.claude/rules/)
Yes → Is it relevant to ALL files?
Yes → Global rule (.claude/rules/rule-name.md)
No → Path-scoped rule (.claude/rules/rule-name.md with paths: frontmatter)This is the most critical step. Write the Incorrect and Correct examples BEFORE writing the description.
Quality check for contrastive examples:
| Check | Pass Criteria |
|---|---|
| Plausibility | Would an agent actually produce the Incorrect pattern? |
| Minimality | Does the Correct pattern change only what is necessary? |
| Clarity | Can a reader identify the difference in under 5 seconds? |
| Specificity | Does each example demonstrate exactly one concept? |
| Groundedness | Are the examples drawn from real codebase patterns? |
Now write the 1-2 sentence description that connects the contrastive examples. The description must:
Create the rule file following the structure template:
title, impact, tags, and optionally pathsPlace the file in .claude/rules/ with a descriptive filename.
Before finishing, verify:
.claude/rules/<rule-name>.mdtitle and impactpaths is set, glob patterns match intended filesAfter a rule is written, apply a Decompose → Filter → Reweight refinement cycle before finalizing:
Consider splitting complex rules into multiple focused rules.
For rules that your written, ask yourself: "Is this rule trying to cover more than one concept?"
For rules that your written, ask yourself: "Could this rule penalize acceptable variations or reward behaviors the prompt does not ask for?"
Check all existing .claude/rules/ files for overlap:
ls -R .claude/rules/ and grep -r "relevant-keyword" to find potential overlapsAssign or reassign the impact frontmatter field based on:
After the refinement cycle, ask the user for feedback on the rule.
You should continue to iterate until the rule is good.
---
title: Use Early Returns to Reduce Nesting
paths:
- "**/*.ts"
---
# Use Early Returns to Reduce Nesting
Handle error conditions and edge cases at the top of functions using early returns. Deeply nested code increases cognitive load and makes logic harder to follow.
## Incorrect
Guard clauses are buried inside nested conditionals, making the happy path hard to find.
\`\`\`typescript
function processOrder(order: Order) {
if (order) {
if (order.items.length > 0) {
if (order.status === 'pending') {
// actual logic buried 3 levels deep
const total = calculateTotal(order.items)
return submitOrder(order, total)
} else {
throw new Error('Order not pending')
}
} else {
throw new Error('No items')
}
} else {
throw new Error('No order')
}
}
\`\`\`
## Correct
Error conditions are handled first with early returns, keeping the happy path at the top level.
\`\`\`typescript
function processOrder(order: Order) {
if (!order)
throw new Error('No order')
if (order.items.length === 0)
throw new Error('No items')
if (order.status !== 'pending')
throw new Error('Order not pending')
const total = calculateTotal(order.items)
return submitOrder(order, total)
}
\`\`\`
## Reference
- [Flattening Arrow Code](https://blog.codinghorror.com/flattening-arrow-code/)---
title: API Endpoints Must Validate Input
paths:
- "src/api/**/*.ts"
- "src/routes/**/*.ts"
---
# API Endpoints Must Validate Input
Every API endpoint must validate request input before processing. Unvalidated input leads to runtime errors, security vulnerabilities, and data corruption.
## Incorrect
The handler trusts the request body without validation, allowing malformed data through.
\`\`\`typescript
export async function POST(req: Request) {
const body = await req.json()
const user = await db.users.create({
email: body.email,
name: body.name,
})
return Response.json(user)
}
\`\`\`
## Correct
Input is validated with a schema before use. Invalid requests receive a 400 response.
\`\`\`typescript
import { z } from 'zod'
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
})
export async function POST(req: Request) {
const parsed = CreateUserSchema.safeParse(await req.json())
if (!parsed.success) {
return Response.json({ error: parsed.error.flatten() }, { status: 400 })
}
const user = await db.users.create(parsed.data)
return Response.json(user)
}
\`\`\`# Bad: No contrastive examples, too vague
Keep functions short and readable.
Use meaningful variable names.Why bad: No concrete boundary. "Short" means different things to different agents. No Incorrect/Correct to calibrate behavior.
# Bad: Multi-step procedure in a rule
When deploying to production:
1. Run all tests
2. Check coverage thresholds
3. Build the project
4. Run integration tests
5. Deploy to staging first
...Why bad: Rules should be constraints, not workflows. This belongs in a skill.
# Bad: Same guidance in two places
# .claude/rules/formatting.md says "use 2-space indent"
# CLAUDE.md also says "use 2-space indent"Why bad: When guidance conflicts, the agent cannot determine which takes precedence. Keep each piece of guidance in exactly one location.
---
paths:
- "**/*"
---Why bad: Equivalent to a global rule but with the overhead of path matching. Remove the paths field entirely for global rules.
title and impact.claude/rules/ with descriptive hyphenated nameEffective rules show, they do not just tell. The Incorrect/Correct contrastive pattern eliminates ambiguity that prose descriptions leave open. When an agent can see both what to avoid and what to produce, compliance improves dramatically.
Every rule should answer three questions:
For larger projects, you can organize instructions into multiple files using the .claude/rules/ directory. This keeps instructions modular and easier for teams to maintain. Rules can also be scoped to specific file paths, so they only load into context when Claude works with matching files, reducing noise and saving context space.
Place markdown files in your project's .claude/rules/ directory. Each file should cover one topic, with a descriptive filename like testing.md or api-design.md. All .md files are discovered recursively, so you can organize rules into subdirectories like frontend/ or backend/:
your-project/
├── .claude/
│ ├── CLAUDE.md # Main project instructions
│ └── rules/
│ ├── code-style.md # Code style guidelines
│ ├── testing.md # Testing conventions
│ └── security.md # Security requirementsRules without paths frontmatter are loaded at launch with the same priority as .claude/CLAUDE.md.
Rules can be scoped to specific files using YAML frontmatter with the paths field. These conditional rules only apply when Claude is working with files matching the specified patterns.
---
paths:
- "src/api/**/*.ts"
---
# API Development Rules
- All API endpoints must include input validation
- Use the standard error response format
- Include OpenAPI documentation commentsRules without a paths field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use.
Use glob patterns in the paths field to match files by extension, directory, or any combination:
| Pattern | Matches |
|---|---|
**/*.ts | All TypeScript files in any directory |
src/**/* | All files under src/ directory |
*.md | Markdown files in the project root |
src/components/*.tsx | React components in a specific directory |
You can specify multiple patterns and use brace expansion to match multiple extensions in one pattern:
---
paths:
- "src/**/*.{ts,tsx}"
- "lib/**/*.ts"
- "tests/**/*.test.ts"
---The .claude/rules/ directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Symlinks are resolved and loaded normally, and circular symlinks are detected and handled gracefully.
This example links both a shared directory and an individual file:
ln -s ~/shared-claude-rules .claude/rules/shared
ln -s ~/company-standards/security.md .claude/rules/security.mdPersonal rules in ~/.claude/rules/ apply to every project on your machine. Use them for preferences that aren't project-specific:
~/.claude/rules/
├── preferences.md # Your personal coding preferences
└── workflows.md # Your preferred workflowsUser-level rules are loaded before project rules, giving project rules higher priority.
dedca19
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.