Taming Claude Code: Essential Tricks to Turn It from Unruly to Powerful
This article walks through the inner workings of Claude Code, explains why it behaves unpredictably out of the box, and provides a step‑by‑step guide—including CLAUDE.md configuration, three operating modes, Hooks, Skills, Agents, and cost‑saving techniques—to transform the tool into a reliable, project‑aware AI coding assistant.
1. How Claude Code Works
Claude Code is not a simple "super Copilot" that executes a single command; its core is a minimal while‑loop that repeatedly calls the model, runs tools, feeds results back, and calls the model again, without any state diagram, task queue, or preset pipeline.
Decision logic occupies only about 1.6 % of the codebase, while the remaining 98.4 % consists of runtime armor such as permissions, compression, tools, and security.
The loop follows the ReAct pattern (Reasoning + Acting) and proceeds in four steps each round.
Because Claude Code is designed to be stateless, every new session starts with a clean context window and has no knowledge of project conventions, protected files, or test requirements. This makes "loss of control" inevitable unless explicit rules are supplied.
Solution: write the rules into a CLAUDE.md file so Claude understands the project from the first message.
2. CLAUDE.md
2.1 What CLAUDE.md Does
CLAUDE.md is read by Claude Code at the start of each session and injected into the system prompt, giving the AI persistent knowledge about the project so you no longer need to repeat background information.
2.2 Four‑layer Configuration Hierarchy
Managed (受管策略) : /Library/Application Support/ClaudeCode/CLAUDE.md – organization‑level enforced policy, managed by IT.
Global (全局) : ~/.claude/CLAUDE.md – applies to all projects on the machine, not version‑controlled.
Project (项目) : ./CLAUDE.md or ./.claude/CLAUDE.md – project‑wide, shared by all team members, must be committed to Git.
Local (本地) : ./CLAUDE.local.md – personal preferences for the project, automatically git‑ignored.
2.3 /init One‑Click Draft Generation
Running /init makes Claude Code automatically scan the local codebase, analyse project structure, dependencies, and tech‑stack, and generate an initial CLAUDE.md in the project root – the fastest way to get Claude up to speed on a new repository.
2.4 Example for a Java Project
# 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/` 目录下的任何文件
- 配置文件只读,不允许自动修改Keep the file under 200 lines; use concise bullet points instead of long paragraphs.
2.5 Modular Rules
For larger projects, split domain‑specific rules into separate markdown files under .claude/rules/:
.claude/
├── CLAUDE.md # main config
└── rules/
├── testing.md # testing related
├── api-design.md # API design guidelines
├── security.md # security constraints
└── database.md # database operation standardsPath filtering can be applied via a paths field in each rule file, e.g.:
paths: "src/main/java/com/example/api/**"Only files matching the pattern will load the rule.
3. Three Working Modes
Default : every file edit or command requires confirmation; ideal for sensitive projects or first‑time encounters.
Auto‑Accept : file modifications are applied automatically while shell commands still need confirmation; best for bulk code changes or code generation.
Plan Mode : read‑only analysis that never modifies files; perfect for exploring unfamiliar codebases.
3.1 Plan Mode – The Recommended “Safety Mode”
Example: migrating a Spring Security configuration across 12 files.
> /plan
> 分析当前项目中 Spring Security 的配置,识别所有需要迁移到新版 SecurityFilterChain 的类,生成迁移计划Claude returns a complete migration checklist and step‑by‑step plan. After confirming the plan, switch to Auto‑Accept for execution.
Recommended workflow: Plan Mode → confirm → Auto‑Accept → back to Default for safety.
3.2 Configure Default Permission Mode
Edit ~/.claude/settings.json to set the default mode, e.g.:
{
"permissions": {
"defaultMode": "acceptEdits"
}
}Use "plan" for unfamiliar codebases.
3.3 Allow and Deny Rules
Explicitly list allowed and denied commands to avoid accidental destructive actions:
{
"permissions": {
"defaultMode": "acceptEdits",
"allow": [
"Bash(git *)",
"Bash(mvn *)",
"Bash(npm *)"
],
"deny": [
"Bash(rm -rf *)",
"Read(.env)",
"Read(.ssh/**)"
]
}
}4. Hooks, Skills, Agents
These three mechanisms turn Claude Code into a "senior engineer with built‑in SOPs".
Hooks = automated guards that run at specific lifecycle events without consuming the context window.
Skills = reusable knowledge packs that encode best practices or domain expertise.
Agents = parallel workers that can execute independent sub‑tasks.
One‑sentence summary: Hooks govern “what not to do”, Skills define “how to do it”, and Agents decide “who does it”.
4.1 Hooks
Claude Code supports nine lifecycle events. Example hooks:
PreToolUse : intercept dangerous operations before they run.
PostToolUse : automatically format code or run linters after a tool finishes.
UserPromptSubmit : inject context or safety warnings when the user submits a prompt.
Other events: Stop, SubagentStop, SessionStart, SessionEnd, PreCompact, Notification.
Configure them in .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": "npx prettier --write $FILE"
}
],
"PreToolUse": [
{
"matcher": "Bash(rm *)",
"command": "echo 'Dangerous operation blocked' && exit 1"
}
]
}
}4.2 Skills
Define a markdown file under .claude/skills/. Example directory structure:
.claude/skills/
└── api-design/
└── SKILL.mdExample SKILL.md content:
---
name: api-design
description: Guide RESTful API design, including URL naming, HTTP methods, and status codes
---
# API Design Guidelines
## URL Naming
- Use plural nouns: /api/v1/users, /api/v1/orders
- Nest resources: /api/v1/users/{userId}/orders
## HTTP Methods
- GET: query, idempotent
- POST: create, non‑idempotent
- PUT: full update, idempotent
- PATCH: partial update, non‑idempotent
- DELETE: delete, idempotent
## Status Codes
- 200: Success
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Server ErrorInvoke with /api-design help me design an order API; the skill is loaded automatically.
4.3 Subagents
Subagents run isolated AI instances for specific tasks, preventing the main session from being polluted with large intermediate results.
Claude Code includes three built‑in subagents:
Explore : read‑only, fast Haiku model for code search.
Plan : read‑only analysis mode.
general‑purpose : versatile subagent.
Create custom subagents via the /agents UI, placing definitions under .claude/agents/ (project scope) or ~/.claude/agents/ (user scope).
5. Cost Management
5.1 Configure Effort Parameter
Anthropic lowered the default effort to “medium” in March 2026, reducing reasoning depth. Restore high effort temporarily with:
> /effort highOr permanently:
export CLAUDE_CODE_DEFAULT_EFFORT=high5.2 Disable Adaptive Thinking
export CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=15.3 Assign Cheaper Models to Subagents
# DeepSeek API configuration
export ANTHROPIC_BASE_URL="https://api.deepseek.com/anthropic"
export ANTHROPIC_API_KEY="sk-YourKey"
# Main agent uses high‑end model
export ANTHROPIC_MODEL="deepseek-v4-pro[1m]"5.4 Everyday Saving Tricks
Switch model per task: /model sonnet for routine work, /model opus for complex tasks (Opus costs 5‑10× more).
Manually trigger compression with /compact when context exceeds 100 K tokens.
Set compression thresholds in settings.json to pre‑compress before hitting limits.
Explicitly tell Claude not to perform web searches to avoid wasted tokens.
Stay in the same session to benefit from prompt cache, reducing cost by ~50‑60 %.
6. 2026 New Features
Dynamic Workflows
Released May 2026, Dynamic Workflows let a single agent split a problem into dozens or hundreds of parallel subagents when the task is too large for one AI.
Trigger by directly asking Claude to "Create a workflow" or enable the Ultracode setting.
/goal Command
Set a condition in /goal; Claude will keep working until the goal is satisfied, a capability shared across major AI coding platforms.
Cross‑Device Seamless Switching
The Claude App on mobile can view and remotely control an active Claude Code session. Generate a QR code with /remote-control and scan it on your phone for real‑time control.
7. End‑to‑End Example: Migrating Logback to Log4j2 in a Spring Boot Project
Step 1 – Initialise Project Memory
cd /your-project
claude
> /init # scans repo and creates CLAUDE.mdStep 2 – Configure Rules
## Log migration constraints
- Do not modify business logic, only logging statements.
- Preserve original log levels (INFO, DEBUG, ERROR, …).
- Replace @Slf4j with an explicit Log4j2 Logger.Step 3 – Plan Mode Confirmation
> /plan
> 分析所有使用 @Slf4j 的 Java 文件,生成完整的迁移清单并提供分批执行计划。Step 4 – Auto‑Accept Execution
> /auto
> 按迁移计划逐批修改文件,每改完一个文件立即执行 mvn compile 验证。Step 5 – Subagent Validation
> 启动子Agent分析整个项目的日志迁移情况。
> 生成报告:已迁移文件列表、遗漏文件、问题文件。8. Pros, Cons, and Suitable Scenarios
Pros
SWE‑bench verified score 80.9 % – best among comparable tools.
Supports up to 1 M tokens, enough for an entire microservice codebase.
Cross‑platform (Windows/macOS/Linux) and model‑agnostic.
Extensible via MCP protocol, Skills, and subagents.
Hooks provide automation without consuming context.
Cons
Higher latency for complex reasoning compared with Copilot or Cursor.
Cost‑sensitive; heavy usage requires careful quota management.
Rules are not foolproof; occasional unexpected behavior still needs human oversight.
Suitable Scenarios
Large codebase refactoring / migration – strongly recommended (long context + subagent isolation).
Cross‑system incident investigation – recommended (deep dependency and call‑graph analysis).
Rapid prototyping / script development – moderate use (higher startup latency).
Routine daily coding – not recommended; traditional assistants are faster.
9. Final Thoughts
Claude Code is not a magic wand; its real value emerges when you engineer it: configure CLAUDE.md, pick the appropriate work mode, and define Hooks, Skills, and Agents so the AI truly understands your project and team conventions.
If your repository lacks a CLAUDE.md, spend ten minutes writing one now. After that, Claude’s output becomes predictable, useful, and aligned with your engineering standards.
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.
SpringMeng
Focused on software development, sharing source code and tutorials for various systems.
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.
