Claude Architect · Leçon

.claude/rules/ avec chemins dans les métadonnées

Chargez les règles uniquement lors de la modification de fichiers correspondants.

Leçon 3 sur 413 étapes

.claude/rules/ avec chemins dans les métadonnées est une leçon Claude Architect gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Claude Architect, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Claude Architect comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

The Monolithic CLAUDE.md Problem

As your project grows, a single CLAUDE.md tends to collect rules for everything: React components, SQL migrations, CI scripts, Terraform. Every one of those rules is loaded into context on every session, even when you are only touching one file type.

That wastes tokens and dilutes attention. The model attends most to the start and end of context (lost-in-the-middle), so a giant rules file can bury the instruction that actually matters for the file you are editing.

.claude/rules/ solves this: split rules into small files that load only when you edit matching files.

How Path-Scoped Rules Work

A rule file lives in .claude/rules/ and starts with a YAML frontmatter block. The key field is paths: a list of glob patterns. The rule body is injected into context only when the files you are working on match one of those patterns.

Think of it as conditional, file-aware instructions. No match means the rule stays out of context entirely, keeping the window lean for the task at hand.

Anatomy of a Rule File

Here is a minimal path-scoped rule. The frontmatter is delimited by --- lines; everything after it is the instruction the model receives when a match occurs.

Because the paths here target test files, this guidance only appears when you are editing tests, not when you touch production code.

---
paths:
  - "**/*.test.tsx"
  - "**/*.test.ts"
---

# Test Conventions

- Use the existing `renderWithProviders` helper, never bare `render`.
- One behavior per `it` block; describe blocks group by component.
- Mock network calls with MSW handlers from `test/mocks/`.

Glob Patterns Are the Trigger

The paths globs are the same style Claude Code's Glob tool uses, for example **/*.test.tsx. A few practical patterns:

  • src/api/** — anything under the API directory
  • **/*.sql — every SQL file in the repo
  • infra/**/*.tf — Terraform only inside infra

Scope tightly. A rule that matches **/* defeats the purpose: it is just your old monolithic CLAUDE.md wearing a frontmatter hat.

Where Rules Sit in the Hierarchy

Path-scoped rules layer on top of the CLAUDE.md hierarchy:

  • User-level ~/.claude/CLAUDE.md — personal, NOT shared via VCS (new teammates miss it).
  • Project-level ./CLAUDE.md or .claude/CLAUDE.md — shared via VCS, always loaded.
  • Directory-level — scoped to a subtree.
  • .claude/rules/ with frontmatter paths — loaded conditionally per matching file.

Keep CLAUDE.md for the few rules that are universally true. Push file-type-specific rules into .claude/rules/.

A Realistic rules/ Directory

Organize rules by concern, one file per file-type or domain. Each carries its own paths, so editing a migration pulls in DB rules while editing a component pulls in React rules, and never the reverse.

# Project layout
.claude/
  CLAUDE.md            # small: universal project facts
  rules/
    react.md           # paths: src/**/*.tsx
    sql-migrations.md   # paths: db/migrations/**/*.sql
    ci-scripts.md       # paths: .github/workflows/**
    terraform.md        # paths: infra/**/*.tf

Migrations Rule Example

Database rules are often strict and easy to forget. Scoping them to migration files means the guidance is in context exactly when it is relevant, and absent when you are writing UI code.

---
paths:
  - "db/migrations/**/*.sql"
---

# Migration Rules

- Every migration must be reversible: include a `-- DOWN` section.
- Never DROP a column in the same migration that stops writing to it.
- Wrap DDL in a transaction; add indexes CONCURRENTLY where supported.
- After inserts, re-sync sequences with setval(...).

Imports vs Path-Scoped Rules

Two ways to modularize, and they are not the same:

  • @path imports inside CLAUDE.md, e.g. @./standards/coding-style.md, always pull that content in. Great for shared standards that apply broadly.
  • .claude/rules/ with paths frontmatter loads conditionally, only when editing matching files.

Rule of thumb: if the guidance applies to a specific file type, scope it with paths. If it applies everywhere, an import (or CLAUDE.md itself) is fine.

<!-- Inside .claude/CLAUDE.md -->
# Project Standards
@./standards/coding-style.md   <!-- always loaded -->
@./standards/commit-format.md  <!-- always loaded -->

<!-- File-type specifics live in .claude/rules/*.md, loaded only on match -->

The Token & Attention Payoff

The win is twofold. First, fewer tokens: irrelevant rule bodies never enter the window, leaving room for the actual code and tool output. Second, sharper attention: the rules present are the ones that match your current files, so the model is not sifting through Terraform conventions while fixing a React bug.

This is the same discipline as trimming verbose tool output to relevant fields, applied to your standing instructions.

Sharing and Secrets

Because .claude/rules/ lives in the repo, it is shared via VCS like project-level CLAUDE.md. New teammates get the same scoped guidance automatically, which user-level ~/.claude/CLAUDE.md would NOT give them.

Treat rule files like code: review them, and never paste secrets. If a rule references an integration, point to env vars such as ${GITHUB_TOKEN} rather than committing a token.

Design Checklist

When you split a monolithic CLAUDE.md into path-scoped rules:

  • One file per file-type or domain; keep each focused.
  • Make paths globs as tight as the rule's true scope.
  • Leave only universal facts in CLAUDE.md; move file-specific rules out.
  • Use @imports for always-on shared standards; paths for conditional ones.
  • Commit to VCS so the team shares the same behavior.

The result is a context window that adapts to whatever file you happen to be editing.

Quick Check: Scoping a SQL Rule

Your CLAUDE.md has grown to 600 lines and most sessions never touch SQL, yet detailed migration rules load every time and crowd out the relevant code. You want those migration rules in context only when editing files under db/migrations/, shared with the whole team. What is the best approach?

Recap

Key takeaways:

  • .claude/rules/*.md with YAML frontmatter paths loads a rule only when editing matching files, saving context and tokens versus a monolithic CLAUDE.md.
  • paths uses Glob-style patterns like **/*.test.tsx or db/migrations/**/*.sql; scope them tightly.
  • Rule files are shared via VCS, unlike user-level ~/.claude/CLAUDE.md.
  • Use @imports for always-on shared standards; use paths frontmatter for conditional, file-type-specific rules.
  • Keep CLAUDE.md small and universal; push file-specific guidance into .claude/rules/ for adaptive, lean context.
Gratuit pour commencer

Apprends Python avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
26
Leçons
104

Questions Fréquemment Posées

La leçon « .claude/rules/ avec chemins dans les métadonnées » est-elle gratuite ?

Oui — le texte complet de « .claude/rules/ avec chemins dans les métadonnées » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Claude Architect, passe à CoddyKit PRO. Le cours Claude Architect comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « .claude/rules/ avec chemins dans les métadonnées » ?

Chargez les règles uniquement lors de la modification de fichiers correspondants. Tu pratiques Claude Architect avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Claude Architect ?

Aucune expérience préalable n'est requise. Claude Architect sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « .claude/rules/ avec chemins dans les métadonnées » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Claude Architect ?

Oui. Chaque leçon Claude Architect inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Niveaux utilisateur, projet et répertoire
  2. Syntaxe d’importation @path
  3. .claude/rules/ avec chemins dans les métadonnées
  4. Règles monolithiques ou modulaires
← Retour à Claude Architect