How to Tame Claude Code: Proven Tricks to Turn It from Unruly to Reliable
This article dissects why Claude Code often behaves unpredictably, then walks through a step‑by‑step configuration of CLAUDE.md, work‑mode switching, Hooks, Skills, and Agents, plus cost‑saving tips and real‑world workflow examples, enabling developers to harness the AI assistant safely and efficiently.
Introduction
Claude Code is marketed as a powerful AI programming assistant, but early users quickly discover that it can act erratically—changing unrelated files, ignoring coding standards, and demanding repeated confirmations.
1. How Claude Code Works
The core of Claude Code is a minimal while loop that repeatedly: (1) invoke the model, (2) run a tool, (3) feed the result back, and (4) repeat. This ReAct (Reasoning + Acting) cycle contains only about 1.6% decision logic; the remaining 98.4% is runtime scaffolding such as permissions, compression, and security.
Because each session starts with a clean context and has no built‑in state, Claude Code treats every new conversation as if it knows nothing about the project, leading to the "out‑of‑control" behavior.
2. CLAUDE.md
CLAUDE.md is a markdown configuration file that is loaded before the first user message, giving Claude persistent knowledge about the project.
2.1 Purpose
When Claude reads CLAUDE.md at session start, it retains project‑wide rules, eliminating the need to repeat background information each time.
2.2 Four‑Layer Configuration System
Managed (organization‑wide) : /Library/Application Support/ClaudeCode/CLAUDE.md (IT‑managed)
Global (user‑wide) : ~/.claude/CLAUDE.md (personal, not version‑controlled)
Project (team‑wide) : ./CLAUDE.md or ./.claude/CLAUDE.md (must be committed to Git)
Local (personal‑only) : ./CLAUDE.local.md (auto‑gitignored)
The project‑level CLAUDE.md must be committed so that new team members inherit the same context after cloning.
2.3 One‑Click Draft Generation with /init
Running /init makes Claude scan the local codebase, infer the project structure, dependencies, and tech stack, and automatically generate a starter CLAUDE.md.
> /init
> Analyze the current Spring Boot project, identify all dependencies, and create an initial CLAUDE.md2.4 Example Java Project CLAUDE.md (≈200 lines)
# Java Spring Boot 项目开发规范
## 构建与运行
- 使用 Maven 3.9+ 构建:`mvn clean install`
- 本地开发运行:`mvn spring-boot:run`
- 跳过测试构建:`mvn clean install -DskipTests`
## 代码规范
- 所有 REST API 返回统一的 Result<T> 包装类
- 使用 Lombok @Data 替代手写 getter/setter
- Service 层统一抛出 BusinessException
- 禁止在 Controller 中写业务逻辑
## 测试要求
- 单元测试覆盖率不低于 80%
- 核心 Service 方法必须有对应的单元测试
## 架构约束
- Controller → Service → Repository 三层架构,禁止跨层调用
- 数据库表前缀统一为 `t_`
## 目录访问限制
- 禁止修改 `/src/main/generated/` 目录下的任何文件
- 配置文件只读,不允许自动修改This concise file tells Claude the mandatory conventions, so it knows what must never be changed.
2.5 Rule Modularity
For larger projects, split domain‑specific rules into .claude/rules/:
.claude/
├── CLAUDE.md # main config
└── rules/
├── testing.md # testing rules
├── api-design.md # API design guidelines
├── security.md # security constraints
└── database.md # database operation rules2.6 Path Filtering Mechanism
Within a rule file you can limit its scope using a paths field, e.g.: paths: "src/main/java/com/example/api/**" Only files matching that pattern will trigger the rule.
3. Three Work Modes
Default : every file edit or command requires confirmation; best for sensitive or unfamiliar codebases.
Auto‑Accept : file modifications are applied automatically while shell commands still need confirmation; ideal for bulk refactoring.
Plan Mode : read‑only analysis; Claude never writes files, making it perfect for architecture reviews.
3.1 Plan Mode – The “Safety Net”
Example: a 12‑file Spring Security migration.
> /plan
> Analyze the current project’s Spring Security configuration, identify all classes that need migration to SecurityFilterChain, and generate a migration plan.Claude returns a complete checklist; after review you switch to Auto‑Accept to execute.
3.2 Configuring the Default Permission Mode
Edit ~/.claude/settings.json to set defaultMode to acceptEdits (trusted repos) or plan (unknown code):
{
"permissions": {
"defaultMode": "acceptEdits"
}
}3.3 Allow and Deny Rules
Specify safe commands and block dangerous ones:
{
"permissions": {
"defaultMode": "acceptEdits",
"allow": ["Bash(git *)", "Bash(mvn *)", "Bash(npm *)"],
"deny": ["Bash(rm -rf *)", "Read(.env)", "Read(.ssh/**)"]
}
}4. Hooks, Skills, and Agents
These three extensions turn Claude into a “self‑documented senior engineer”.
Hooks : automated guards that run at specific lifecycle events (e.g., pre‑tool use, post‑tool use). They do not consume context tokens.
Skills : reusable knowledge packages written as markdown files that Claude can load on demand.
Agents : parallel workers that execute isolated sub‑tasks without polluting the main session’s context.
4.1 Hooks – Automated Guardrails
Claude supports nine lifecycle events. Example configuration in .claude/settings.json:
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"command": "npx prettier --write $FILE"
}],
"PreToolUse": [{
"matcher": "Bash(rm *)",
"command": "echo '危险操作被拦截' && exit 1"
}]
}
}This automatically formats code after edits and blocks dangerous rm * commands.
4.2 Skills – Reusable Knowledge Packs
Place a skill under .claude/skills/:
.claude/skills/
└── api-design/
└── SKILL.mdSample SKILL.md:
---
name: api-design
description: 指导 RESTful API 设计规范,包括 URL 命名、HTTP 方法选择、状态码使用
---
# API 设计规范
## URL 命名
- 使用名词复数:/api/v1/users
- 资源嵌套:/api/v1/users/{userId}/orders
## HTTP 方法
- GET:查询,幂等
- POST:创建,非幂等
- PUT:全量更新,幂等
- PATCH:部分更新,非幂等
- DELETE:删除,幂等
## 状态码
- 200:成功
- 201:创建成功
- 400:参数错误
- 401:未认证
- 403:无权限
- 404:资源不存在
- 500:服务器错误Invoke with /api-design 帮我设计一个订单 API.
4.3 Subagents – Isolated Workers
Subagents run in separate contexts, preventing token bloat. Claude ships with three built‑in subagents:
Explore : read‑only, fast Haiku model for code search.
Plan : read‑only, used in Plan Mode.
general‑purpose : versatile worker.
Custom subagents can be created via /agents and placed in .claude/agents/ (project) or ~/.claude/agents/ (user).
5. Quota Management
Claude Code can consume large amounts of token budget. The following tricks reduce cost:
Force high effort : /effort high or set CLAUDE_CODE_DEFAULT_EFFORT=high to avoid the default medium setting introduced in March 2026.
Disable adaptive thinking : export CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1 to keep a fixed inference budget per round.
Model per subagent : point cheap models (e.g., DeepSeek) to subagents while keeping the main agent on a high‑quality model.
General cost‑saving tips :
Switch models per task ( /model sonnet for routine, /model opus for complex).
Manually trigger compression with /compact before the 100 KB limit.
Set compression thresholds in settings.json to pre‑compress.
Avoid unnecessary web searches by explicitly telling Claude not to search.
Leverage prompt cache by staying in the same session (reduces cost 50‑60%).
6. 2026 New Features
Dynamic Workflows
Released May 2026, Dynamic Workflows let Claude split a problem into dozens of parallel subagents within a single session.
Two activation methods:
Ask Claude to “Create a workflow”.
Enable the “Ultracode” setting in the effort menu.
/goal – Ensure Completion
Setting a goal forces Claude to keep working until the condition is satisfied, a capability shared across major AI labs.
Cross‑Device Remote Control
Use /remote-control to generate a QR code; the Claude mobile app can then view and control the active session.
7. End‑to‑End Practical Workflow
Scenario: migrate a Spring Boot project from Logback to Log4j2.
Step 1 – Initialise Project Memory
cd /your-project
claude
> /init # scans codebase and creates CLAUDE.mdStep 2 – Add Hard Constraints
## 日志迁移约束
- 严禁修改业务逻辑,只改日志声明
- 保持原始日志级别不变
- 若使用 @Slf4j,改为显式 Log4j2 LoggerStep 3 – Plan Mode Review
> /plan
> 分析所有使用 @Slf4j 的文件,生成迁移清单并给出分批执行计划Step 4 – Auto‑Accept Execution
> /auto
> 按迁移计划逐批修改,每改完一个文件立即运行 mvn compile 验证Step 5 – Subagent Verification
> 启动子Agent分析整体迁移情况
> 生成报告:已迁移文件、遗漏文件、问题文件8. Pros, Cons, and Suitable Scenarios
Advantages
SWE‑bench verified score 80.9 % – top among code‑fix tools.
Supports >1 million token context, fitting entire micro‑service codebases.
Cross‑platform (Windows/macOS/Linux) and model‑agnostic.
Extensible via MCP protocol, Skills, and subagents.
Hooks add automation without consuming context tokens.
Disadvantages
Higher latency for complex reasoning compared with Copilot/Cursor.
Cost‑sensitive – heavy usage requires careful quota management.
Rule files are not foolproof; occasional “self‑assertion” still needs human oversight.
Applicable Scenarios
Large code‑base refactoring / migration – strongly recommended (needs long context and subagents).
Cross‑system incident investigation – recommended (excellent dependency tracing).
Rapid prototyping / script development – moderate use (startup overhead).
Routine daily coding – not recommended (Copilot/Cursor faster and cheaper).
9. Conclusion
Claude Code is not a magic bullet; its real value emerges when you engineer it with CLAUDE.md, the three work modes, and the Hooks/Skills/Agents framework, turning the assistant into a project‑aware, rule‑compliant AI partner.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
