# Apply path-specific rules for conditional convention loading

Load conventions for matching files through explicit path conditions and checked patterns.
Learn when path-specific rules suit scattered file types and when directory instructions suit a subtree. Testing and infrastructure examples demonstrate included and excluded paths, while diagnosis separates a saved rule, actual loading, and compliance.

Author: LearningPathX Editorial Team
Content version: 1.0
Published: 2026-12-04T00:30:47.990366+00:00
HTML: https://learningpathx.com/material/CCAR-F/apply-path-specific-rules-for-conditional-convention-loading.html

Knowledge domain: Claude Code Configuration & Workflows
Tags: Instruction Design / Configuration Management / Path-Specific Rules

## Apply path-specific rules for conditional convention loading

## Learning objectives

Define conditional rules with YAML path patterns, choose between path rules and directory instructions, and diagnose a rule that does not activate. Distinguish relevant guidance from an enforced security boundary.

## Make the loading condition explicit

A path-specific rule is a Markdown instruction file under `.claude/rules/` with a YAML `paths` field. Its patterns identify files to which the instructions apply. In the supplied materials, the rule becomes relevant when matching file content is read; it is not activated by every tool call or merely by seeing a filename in a directory listing.

A rule without path scoping is broad project guidance. Moving a file into a subfolder named `testing` within the rules directory organizes the files for maintainers, but does not itself make the instructions conditional on test files. The path condition must be expressed in frontmatter.

Conditional loading can defer unrelated rule text until a matching-file read, reducing irrelevant initial inclusion. Once text has been included, moving to a different file does not by itself show that earlier guidance was removed: conditional applicability does not guarantee automatic unloading. Inspect actual current context before claiming removal or measured token savings. Matching instructions still consume context when loaded, and inclusion does not establish compliance. Permission controls and tests remain separate mechanisms.

## Choose patterns that express the intended set

A glob is a path pattern, not a regular expression. Interpret it relative to the rule system's project scope and check the actual matching behavior rather than assuming that similar-looking syntax has the same meaning in every tool.

| Pattern | Intended scope in the supplied materials |
| --- | --- |
| `**/*.ts` | TypeScript files across directories |
| `src/**/*` | Files below `src/` |
| `*.md` | Markdown files at the project root |
| `src/components/*.tsx` | TSX files directly in that component directory |

A single `*` and a recursive `**` express different directory reach. The pattern `src/components/*.tsx` should not be used when the requirement includes arbitrarily nested component folders. A broader pattern can also load irrelevant guidance, so test both included and excluded paths.

For a concrete teaching tree, assume project-root-relative patterns and a dialect where `**` can cover zero directories. The files are `index.ts`, `src/core/value.ts`, `src/ui/View.tsx`, `src/ui/view.js`, `README.md`, `docs/guide.md`, `src/components/Card.tsx`, `src/components/nested/Card.tsx`, `src/components/Card.jsx` and `other/helper.ts`. Here `**/*.ts` includes `index.ts`, `src/core/value.ts` and `other/helper.ts`, but excludes every listed `.tsx`/`.js`/`.jsx` file. `src/**/*` includes every listed file below src, including the nested component, and excludes `index.ts`, both Markdown paths and `other/helper.ts`. `*.md` includes `README.md` and excludes `docs/guide.md`; `src/components/*.tsx` includes `src/components/Card.tsx` but excludes `src/components/nested/Card.tsx` and `src/components/Card.jsx`. These are expected name-pattern decisions for the declared tree and dialect, not actual client discovery or proof of code semantics.

Quote patterns in YAML, particularly when they contain characters with YAML meaning. Keep lists simple. Brace expansion can multiply the number of patterns substantially. The source describes expansion budgets and version-dependent handling of malformed brackets and symlinks; these are implementation limits to inspect in the target environment, not portable glob guarantees. Prefer a few clear patterns over a large combinatorial expression.

## Apply one convention across scattered files

Use directory-level `CLAUDE.md` when the convention belongs to a package or subtree: for example, all work in a storage package may share transaction rules. Use a path-specific rule when the convention follows a file type or naming convention across unrelated packages.

Here CLAUDE means the persistent `CLAUDE.md` instruction file, not the model. In the adopted hierarchy snapshot, `CLAUDE.md` and `CLAUDE.local.md` along the ancestor chain above the working directory load in full at launch; descendant instruction files load on demand when files in those directories are read. Persistence therefore does not mean every nested instruction file loads at every startup, nor that instructions are obeyed. This directory-scope mechanism is distinct from selecting a cross-directory file pattern.

Suppose tests exist in `src/cart/`, `packages/catalog/`, and a top-level integration folder. Copying the same testing paragraph into three directory instruction files creates multiple places to update. One rule for the relevant test suffixes expresses the cross-directory requirement in a single maintained location.

Path rules and directory guidance can both be relevant to a file. Make their responsibilities compatible: the package instruction can describe domain constraints while the test rule describes evidence expected from every matching test. Do not assume that a filename pattern resolves contradictory instructions automatically.

## Worked example: a shared testing rule

Save this illustrative file as `.claude/rules/testing.md`:

```yaml
---
paths:
  - "**/*.test.ts"
  - "**/*.spec.tsx"
---
# Testing conventions
Use descriptive test titles that state the behavior being checked.
Mock external services so that local tests do not depend on live credentials.
Include a failure case when the changed behavior can reject input.
```

The intended path decisions are explicit:

| File being read | Should this rule apply? | Reason |
| --- | --- | --- |
| `src/cart/cart.test.ts` | Yes | Matches the first suffix pattern |
| `packages/catalog/view.spec.tsx` | Yes | Matches the second suffix pattern |
| `src/cart/cart.ts` | No | Production file, neither suffix |
| `README.md` | No | Neither suffix |

A filename listing containing `cart.test.ts` is not the same as reading its content. For an installation-level acceptance check, inspect the loaded rule when reading a matching file, then compare a nonmatching file. Merely producing the table does not demonstrate that Claude Code loaded the configuration.

If the actual project uses `.test.tsx` as well, the illustrated rule is incomplete for that project. Add an explicit corresponding pattern after confirming the requirement. Do not claim that `.spec.tsx` automatically covers every TSX test naming convention.

## Worked example: infrastructure guidance

A rule scoped to `"terraform/**/*"` applies to files under that directory in the described model. A narrower `"terraform/**/*.tf"` targets Terraform source files. These are different choices: the broader pattern may also match documentation or helper files there. Select the one that matches the stated convention.

If root-level `.tfvars` files also require guidance, add a separate pattern for them. A rule confined to `terraform/` cannot establish coverage of a root-level file. Conversely, avoid broadening all repository files when only those configuration inputs need the instruction.

## Diagnose missing or excessive loading

Start with the saved file: confirm its location, valid frontmatter delimiters, a properly formatted `paths` list, and the actual path to be matched. Then inspect whether the matching file was read, which project and configuration sources the session uses, and whether project rules are enabled.

If a simple pattern works and a complex one does not, reduce the expression and inspect escaping, bracket syntax, and expansion limits. For a symlinked rule or checkout, confirm that the target exists and resolves to the intended content under the active environment's behavior. Do not use an assumed version fix as evidence of successful loading.

If the rule loads too broadly, check for missing `paths`, an accidentally broad glob, or an unconditional duplicate elsewhere. Verify both the active instructions and the actual output behavior. Guidance that loads correctly can still be ignored or conflict with another rule; loading and compliance are separate findings.

## Read source-specific limits as source-specific limits

All exact release and interface details here come from the supplied snapshot. Its original cited anchor attachments were not supplied, and no current-client glob/loading test was performed. D03 factual context takes precedence over glossary terminology; the glossary's Path Scoping entry is marked needs\_review and does not independently verify a matcher.

The described client discovers `.md` rules recursively under `.claude/rules/`. An accepted rule without `paths` loads at launch with root `.claude/CLAUDE.md` project priority. A valid conditional rule requires supported frontmatter, an enabled project source and an actual matching-file read. A visible textual `paths` key does not prove the parser accepted its type or syntax. Deliberately absent metadata, malformed metadata, a wrongly typed value, a valid nonmatch and disabled project rules are distinct states; inspect the actual parsed state rather than assume a safe fallback.

For the testing example above, reading root `cart.test.ts` is also an expected positive for `**/*.test.ts`. Reading `src/cart/cart.test.tsx` is negative for both listed patterns, as is `src/cart/cart.spec.ts`. Those suffixes require additional explicitly selected patterns if the actual project needs them. A `.ts` extension does not include `.tsx` or `.js`, and a component `.tsx` pattern does not cover every possible React source format.

## Explain small expansions before considering limits

The source's `src/*.{ts,tsx}` example has two alternatives: `src/*.ts` and `src/*.tsx`. It does not include JavaScript. Its `{a,b}/{c,d}/*.{ts,tsx}` example combines three independent two-way choices, so 2 × 2 × 2 = 8:

```text
a/c/*.ts
a/c/*.tsx
a/d/*.ts
a/d/*.tsx
b/c/*.ts
b/c/*.tsx
b/d/*.ts
b/d/*.tsx
```

This is expected alternative enumeration under the declared example, not a runtime test. U02 remains explicitly pending: the snapshot asserts a shared whole-rule budget of 1,000 expanded patterns and 4 MiB, a brace-free exemption and unexpanded over-budget fallback, but these exact capacity/fallback details have not been independently confirmed. Its reported pre-v2.1.217 brace-stability problem is also a source-scoped release claim. Keep patterns small and inspect actual supported limits. A small eight-member calculation does not verify an implementation budget; do not infer that every literal-brace string is impossible to match any filename. U01's exact import recursion cutoff remains pending in the separate hierarchy/import topic.

## Keep bracket and link cases distinct

The source uses `[abc]` as a bracket class and `photos [2024/**` as an unclosed invalid expression. Some rendered passages repeat that identical malformed text as the supposed literal-bracket escape, while a later tip says to use a backslash. That is a source rendering inconsistency, not a demonstrated working correction. A literal bracket in a filename is different from a character class. Correct treatment depends on the actual glob dialect and the YAML/string encoding layer. No exact literal-bracket correction was tested here; inspect an accepted encoded pattern and concrete intended-match/nonmatch outcomes before calling it working.

The snapshot distinguishes these release cases:

| Case | Source-attributed condition |
| --- | --- |
| Target reached through a symlinked checkout path | Matching support reported from v2.1.198 |
| Rule-file/rule-directory symbolic links | Described as resolved normally, with circular links detected |
| Invalid unclosed bracket | Before v2.1.207, could fail Read for evaluated files; later described as a nonmatch while other valid patterns continue |
| Project source excluded with `--setting-sources` | Project rules skipped in the described supported path; pre-v2.1.211 lazy/nested rules reportedly could still load |

These are distinct source claims, not tested guarantees. Check the actual rule link target, target-file identity, access authority, accepted pattern, release and loaded context. Symlinks do not confer permission to read outside the authorized scope. A missing target, parse error, ordinary nonmatch, excluded source and untriggered read require different diagnoses. CLI expands to Command Line Interface; that expansion alone verifies neither the source flag/release behavior nor the actual loaded rule state.

## A complete infrastructure-rule illustration

The source's rendered `--`/list-marker frontmatter is not valid runnable YAML. This repaired example at `.claude/rules/infrastructure.md` deliberately covers nested Terraform source and root-level variable files:

```markdown
---
paths:
  - "terraform/**/*.tf"
  - "*.tfvars"
---
# Infrastructure conventions
For the source's team-collaboration scenario, use the project's approved remote state backend.
Before committing a Terraform change, run the project's approved `terraform fmt` check.
Report whether formatting actually ran and its outcome; loaded guidance is not execution evidence.
```

Assume the stated project-root pattern dialect, accepted metadata and enabled project source:

| File content read | Expected rule applicability |
| --- | --- |
| `terraform/main.tf` | Yes, Terraform source |
| `terraform/env/prod/main.tf` | Yes, nested Terraform source |
| `prod.tfvars` | Yes, root variable file |
| `terraform/README.md` | No, not .tf |
| `env/prod.tfvars` | No, the chosen \*.tfvars is root-only |
| `src/App.tsx` | No, neither chosen pattern |

The broader `terraform/**/*` would include documentation/helpers below that directory; it is a different convention population. A component rule `src/components/*.tsx` would target directly contained TSX files, while nested components need an explicitly recursive pattern. Neither rule automatically executes formatting or enforces compliance. The table states expected decisions only; verify actual matching reads and included instructions in the supported installation. The source React illustration advises functional components with hooks and prop typing using TypeScript interfaces. Those are illustrative framework conventions, not evidence that type checking, tests or a component migration executed.

## Summary

Use frontmatter path conditions for conventions that follow files across the repository, and directory instructions for conventions tied to a subtree. Test representative matches and exclusions, keep patterns understandable, and verify actual loading before treating a rule as operational.
