iTranslated by AI
Mastering CLAUDE.md Design for Claude Code: Building a Resilient Rule System That Scales
Introduction
Claude Code is smart. However, if you don't give it any instructions, it becomes a "polite but verbose, expensive assistant that forgets everything across sessions."
If you write rules in CLAUDE.md, its behavior changes. But what happened as a result of continuously adding rules? The configuration file bloated, consuming a large number of tokens in every session, reducing the context available for the actual work.
This article describes the transition from "V1," where rules were added ad hoc, to "V2," rebuilt based on infrastructure design and management principles, complete with the actual configuration files.
Key Points of This Article
- Treat Claude Code configuration as a design subject, just like "code."
- Deciding what not to have AI do is the most effective way to reduce token consumption.
- Infrastructure design principles (loose coupling, separation of concerns, regular inventory) apply directly to AI configuration.
The V1 Era: Rules Increased, But There Was No System
When I first started using Claude Code, the configuration was created like this:
- Open URLs that seemed useful and look at other people's CLAUDE.md files.
- Add rules that seemed good to my own CLAUDE.md.
- Encounter dissatisfaction while using it (output is verbose, it responds in English, it forgets across sessions).
- Add rules to resolve the dissatisfaction.
- Repeat steps 2 through 4.
This itself isn't wrong. Working rules accumulate over time. The problem arose as the number of rules increased.
Problems That Occurred
Bloated configuration file. Individual rules like "Respond in Japanese," "Commit messages should also be in Japanese," "No greetings," and "Don't list file contents" lined up in CLAUDE.md. Project-specific rules and global settings were mixed in the same file.
Increased token consumption. CLAUDE.md is read every time a session starts. The larger the file, the less context is available for work. When looking at monthly token consumption across two projects, a significant portion was taken up by reading the configuration file and verbose output.
Contradictions between rules. Adding rules ad hoc leads to conflicting rules coexisting, like "Be concise" and "Always explain the reason." The AI faithfully tries to follow both, resulting in mediocre output.
The V1 rules were individually correct. However, they lacked a structure for "when, where, and why to apply them."
The Turning Point: Realizing Tokens Are Money
The other day, I saw a post on my X timeline about "offloading work that AI is doing to Python scripts."
That line hit home. Reflecting on my own projects, most of the work I was having AI do could be done without AI.
- Listing files →
lssuffices - Aligning text formatting → a shell script suffices
- Checking if code follows coding conventions → a linter suffices
- Cost aggregation → a Python script suffices
Using AI tokens for these tasks is like having a million-dollar-a-year engineer manually enter data into Excel.
The V1 rules don't need to be discarded. However, it is necessary to separate what AI should do from what it shouldn't and structurally reduce token consumption.
So, I decided to apply the infrastructure design and management principles I've been using in the field directly to this.
V2 Design: Four Principles
Principle 1: Separation of Concerns (5-Layer Architecture)
Clearly define what AI should do.
| Layer | Name | Role |
|---|---|---|
| L5 | Meta (self-improvement) | AI improves settings and rules themselves |
| L4 | Validation (review) | Quality checks, linting |
| L3 | Creative (judgment) | Thinking, judging, writing |
| L2 | Skill (MCP) | Tool integration, API calls |
| L1 | Infrastructure (execution) | File operations, aggregation, formatting |
AI is responsible only for L3 and L5. L1, L2, and L4 are delegated to Python or shell scripts.
For example, L4 validation. Having AI perform a quality check on articles every time consumes thousands of tokens. However, if the check items are standardized, a Python script (lint-ai-style.py) can mechanically score them. AI only needs to intervene at L3, the part where it "judges what to fix and how" when the score exceeds a threshold.
Similarly for L1. Cost aggregation and repository health checks are delegated to cost-report.py or health-check.py. AI only reads the results and makes decisions.
Write this in CLAUDE.md:
AI = expensive CPU. Delegate toil (search, calculation, parsing, copy-paste, etc.) to Python/Shell/MCP.
If a human tries to have AI perform toil, propose scripting and refuse.
The last line is important. When the human (yourself) is tempted to "have AI do this too," the AI suggests, "Let's script that." Incorporate guardrails into the configuration.
Principle 2: Loose Coupling (3-Layer Separation of Configuration)
In V1, all rules were in a single CLAUDE.md file. In V2, they are separated into three layers.
| Layer | File | Content | Change Frequency |
|---|---|---|---|
| Global | ~/.claude/CLAUDE.md |
Common behavioral guidelines for all projects | About once a month |
| Project | <project>/CLAUDE.md |
Project-specific policies | About once a week |
| Hard Rules | <project>/.clauderules |
Constraints that must never be broken | Almost never |
The global configuration holds only rules that apply to any project, such as "Respond in Japanese," "Token economics," and "5-layer architecture."
The project's CLAUDE.md contains only the project's specific mission and references. Detailed specifications are separated into other files (architecture.md or config/strategy.md), and CLAUDE.md only references them. This minimizes the token consumption of the configuration files themselves.
.clauderules contains only rules that must never be broken, such as data protection and loop prevention.
# .clauderules — Hard Rules
## Production Protection
- Only file moves to publish_queue/ that have passed review judgment
- Do not delete or move files in escalation/ until a human confirms
## Infinite Loop Prohibition
- Maximum 2 rework cycles on the same file. Isolate and stop after the 2nd
This way, even if a new rule is needed for a project, it does not affect the global configuration. Adding or removing rules is completed within the project scope.
Principle 3: Cost-Effectiveness (Token Economics)
Explicitly state the idea that "context is debt."
## Token Economics
- Context is debt. Complete 1 task → Write state to file → /clear
- Scriptize immediately upon discovering routine work
- Keep total configuration files minimal. Prohibit verbose repetition and greetings
It's the same as technical debt. The more information in the context window, the less capacity there is to process new information. When a task is complete, write the state to a file and /clear. Start the next task with a clean context.
"Prohibit verbose repetition and greetings" is subtly effective. The default Claude Code outputs preambles like "Understood. I will now check ○○." Just prohibiting this saves several hundred tokens per session.
Principle 4: Regular Inventory
Both configuration and code rot if left unattended.
## Session Management (Checkpointer)
- At start: If CLAUDE.local.md exists, check the handover memo and report at the beginning
- At end: Write carry-over information to CLAUDE.local.md in 3 lines or less. Delete completed items
CLAUDE.local.md (gitignored) is used as a handover memo between sessions. Instead of telling AI "how far you got last time," have it read what's written in the file.
Also set standards for information freshness.
## Information Freshness Standards
- CVE (CVSS 7+): 2 weeks
- Low importance, versions: 1 month
- Trends: 3 months
- For information exceeding these, additionally confirm the latest status
It's problematic if AI writes code based on "information seen on X more than 3 months ago." Have it reconfirm stale information before using it.
Auxiliary Design: Turning Failures into Organizational Knowledge
Among the new files in V2, the one with the highest cost-effectiveness was known-failures.md.
# known-failures — Collection of Command Failure Patterns
## Git Operations (WSL/Windows Environment)
| Goal | NG | OK |
|---|---|---|
| Change global config | `git config --global` (blocked by hook) | Pass `git -c key=value` directly |
| Push to remote | SSH | Configure for HTTPS |
## Commands Blocked by Hook
| NG | Alternative |
|---|---|
| `curl * | bash` | WebFetch tool |
| `npm install -g *` | `npm install` in project local |
AI repeats the same failures over and over. Because memory is erased when a session changes. By writing "NG → OK" patterns in known-failures.md, AI checks this file before executing Bash commands and avoids known failure patterns.
This is the same idea as post-mortems in infrastructure operations. When an incident (command failure) occurs, record the cause and document preventive measures (alternative commands). What is done in human organizations is brought directly into AI configuration.
Another Auxiliary Design: Template-Based Coding Standards
In coding-standards.md, I write Bash script templates and commit message conventions.
## Bash Script — Template
#!/bin/bash
set -euo pipefail
# --- Constants ---
PROJECT_DIR="/path/to/project"
LOG_PREFIX="[$(date +%Y-%m-%d) $(date +%H:%M:%S)]"
echo "${LOG_PREFIX} ===== Start Processing ====="
Why have a template? AI writes code in slightly different styles each time. It may or may not include set -euo pipefail, and the log format varies. By specifying a template, the quality of generated code becomes consistent.
The key is to always write why the rule exists.
| Rule | Reason |
|---|---|
Write set -euo pipefail at the top |
Prevent undefined variables and suppressed pipe errors |
Quote variables with "${VAR}"
|
Prevent accidents with paths containing spaces |
| Write the cron registration command in a header comment | Instantly know "when it runs" |
Having reasons allows AI to make correct judgments even in edge cases. Simply writing "Write set -euo pipefail" might lead AI to mechanically insert it into function definition files or scripts that are only sourced. By adding "to prevent suppressed undefined variable errors," AI can infer that it's unnecessary for source-only files.
What Changed from V1 to V2
Perceived Changes
AI autonomy increased. With the 5-layer architecture clearly defining "what to do" and "what not to do," AI began to proactively suggest, "Let's script this," on its own judgment. In V1, things that only moved when a human instructed became spontaneous due to being incorporated into the configuration.
Cross-session consistency improved. Handover memos via CLAUDE.local.md and failure pattern recording via known-failures.md ensured consistent quality across sessions.
Adding and modifying rules became easier. With loose coupling, I started thinking "Is this rule global or project-specific?" before adding it. As a result, rule bloat stopped.
Conclusion
If left unattended, Claude Code configuration becomes bloated with ad hoc rules. That's a natural phenomenon. It starts with rules that solve individual problems.
The problem is that the more rules there are, the more tokens are consumed, and AI performance degrades. This is where the phrase "treat configuration as a design subject" comes in.
The principles applied in V2 are nothing special.
- Separation of concerns: Limit what AI should do (5-layer architecture)
- Loose coupling: Separate configuration into global, project, and hard rules
- Cost-effectiveness: Context is debt. Structurally reduce token consumption
- Regular inventory: Prevent configuration rot with session management and information freshness standards
These are just the ideas used in infrastructure design and management, applied directly to AI configuration.
One final note. The rules accumulated in V1 were not wasted. "Respond in Japanese," "No greetings," "Explain the reason"—these are still alive in V2. What V2 did was not discard individual rules, but rearrange them into appropriate places.
Configuration is not "write and forget." It is something to design, refactor, and inventory, just like code.
Actual Configuration Files
The actual V2 design constitution introduced in this article is published on GitHub.
Discussion