
Claude Code You Don't Know: Architecture, Governance, and Engineering Practices
0. TL;DR
This article stems from deep experience using Claude Code over the past six months, paid for with two accounts at $40 per month, and the pitfalls encountered along the way. I hope it provides some useful input for everyone.
Initially, I used it as a chatbot, but soon realized something was off: the context became increasingly messy, tools multiplied but results worsened, and rules grew longer yet were followed less. After some tinkering and studying Claude Code itself, I realized this wasn't a prompt problem—it's how the system is designed.
This article aims to discuss several things: how Claude Code works under the hood, why context gets messy and how to manage it, how to design Skills and Hooks, the correct use of Subagents, the architectural impact of Prompt Caching, and how to write a truly useful CLAUDE.md.
I think the most direct way to understand it is to break Claude Code into six layers:

Strengthening only one layer unbalances the system: writing CLAUDE.md too long pollutes the context first; stacking too many tools confuses selection; spawning subagents everywhere causes state drift; skipping verification means you can't tell where things went wrong.
1. How It Works Under the Hood

The core of Claude Code isn't "answering"—it's a repetitive agentic loop:
textGather context → Take action → Verify results → [Done or back to gather] ↑ ↓ CLAUDE.md Hooks / Permissions / Sandbox Skills Tools / MCP Memory
After using it for a while, I realized that bottlenecks almost never come from the model not being smart enough; more often, it's giving it the wrong context, or producing output that can't be verified or rolled back.
The Five Layers That Truly Matter:

Looking at these layers makes many issues easier to diagnose. Unstable results? Check context loading order—it's not the model. Automation running wild? See if the control layer is designed—it's not the agent being too proactive. Quality degrading in long sessions? Intermediate artifacts are polluting the context; starting a new session is more useful than repeatedly tweaking prompts.
2. Conceptual Boundaries: MCP / Plugin / Tools / Skills / Hooks / Subagents

Simple rule: use Tool/MCP to give Claude new action capabilities, Skill to give it a working methodology, Subagent for isolated execution environments, Hook for enforced constraints and auditing, and Plugin for cross-project distribution.
3. Context Engineering: The Most Important System Constraint
Many people treat context as a "capacity issue," but bottlenecks usually aren't about length—it's noise. Useful information gets drowned out by irrelevant content.
The Real Cost Structure of Context

Claude Code's 200K context isn't fully usable:
text200K total context ├── Fixed overhead (~15-20K) │ ├── System instructions: ~2K │ ├── All enabled Skill descriptors: ~1-5K │ ├── MCP Server tool definitions: ~10-20K ← biggest hidden killer │ └── LSP state: ~2-5K │ ├── Semi-fixed (~5-10K) │ ├── CLAUDE.md: ~2-5K │ └── Memory: ~1-2K │ └── Dynamically available (~160-180K) ├── Conversation history ├── File contents └── Tool call results

A typical MCP Server (like GitHub) contains 20-30 tool definitions, each around 200 tokens, totaling 4,000-6,000 tokens. Connect 5 servers, and that fixed overhead alone reaches 25,000 tokens (12.5%). When I first calculated this, I was surprised at how much it was. In scenarios requiring heavy code reading, that 12.5% really matters.
Recommended Context Layering
textAlways resident → CLAUDE.md: project contract / build commands / prohibitions Path-based loading → rules: language / directory / file-type specific rules On-demand loading → Skills: workflows / domain knowledge Isolated loading → Subagents: extensive exploration / parallel research Never in context → Hooks: deterministic scripts / auditing / blocking
In short, don't load things you use occasionally every time.
Context Best Practices

The Pitfalls of the Compaction Mechanism
The default compaction algorithm judges based on "re-readable," so early Tool Outputs and file contents get deleted first, taking architectural decisions and constraint rationales with them. Two hours later, you might not remember what you decided, and that's how mysterious bugs arise.

The solution is to specify in CLAUDE.md:
markdown## Compact Instructions When compressing, preserve in priority order: 1. Architecture decisions (NEVER summarize) 2. Modified files and their key changes 3. Current verification status (pass/fail) 4. Open TODOs and rollback notes 5. Tool outputs (can delete, keep pass/fail only)
Beyond writing Compact Instructions, there's a more proactive approach: before starting a new session, have Claude write a HANDOFF.md that records current progress, what was tried, what worked, what was a dead end, and what to do next. The next Claude instance can just read this file and continue, without relying on the compaction algorithm's summary quality:
Write down the current progress in HANDOFF.md. Explain what you tried, what worked, what didn't, so that the next agent with fresh context can continue the task just by reading this file.
After writing, quickly scan it; if there are gaps, have it fill them, then start a new session and pass the HANDOFF.md path.
The Engineering Value of Plan Mode

Plan Mode's core is separating exploration from execution: exploration doesn't touch files, and execution only happens after the plan is confirmed:

For complex refactors, migrations, or cross-module changes, this is far more useful than "rushing out code." It significantly reduces the probability of iterating on wrong assumptions. Press Shift+Tab twice to enter Plan Mode. An advanced trick is to have one Claude write the plan and another Codex review it as a "senior engineer," letting AI review AI—it works well.
4. Skills Design: Not a Template Library, but On-Demand Workflows
The official description of Skills is "on-demand knowledge and workflows." Descriptors stay resident in context, while full content loads on demand—quite different from "saved prompts."
What Makes a Good Skill
How Skills Achieve On-Demand Loading
The Claude Code team repeatedly emphasizes "progressive disclosure" in internal design—not showing the model everything at once, but first providing an index and navigation, then pulling details on demand:
A stable structure looks like this:
text.claude/skills/ └── incident-triage/ ├── SKILL.md ├── runbook.md ├── examples.md └── scripts/ └── collect-context.sh
Three Typical Types of Skills
The following examples are from my actual Skills in the open-source terminal project Kaku, which are quite intuitive.
Type 1: Checklist Type (Quality Gate)
Run before a release to ensure nothing is missed:
yaml--- name: release-check description: Use before cutting a release to verify build, version, and smoke test. --- ## Pre-flight (All must pass) - [ ] `cargo build --release` passes - [ ] `cargo clippy -- -D warnings` clean - [ ] Version bumped in Cargo.toml - [ ] CHANGELOG updated - [ ] `kaku doctor` passes on clean env ## Output Pass / Fail per item. Any Fail must be fixed before release.
Type 2: Workflow Type (Standardized Operation)
High-risk config migration with explicit invocation and built-in rollback steps:
yaml--- name: config-migration description: Migrate config schema. Run only when explicitly requested. disable-model-invocation: true --- ## Steps 1. Backup: `cp ~/.config/kaku/config.toml ~/.config/kaku/config.toml.bak` 2. Dry run: `kaku config migrate --dry-run` 3. Apply: remove `--dry-run` after confirming output 4. Verify: `kaku doctor` all pass ## Rollback `cp ~/.config/kaku/config.toml.bak ~/.config/kaku/config.toml`
Type 3: Domain Expert Type (Encapsulated Decision Framework)
When runtime issues occur, let Claude collect evidence along a fixed path without guessing:
yaml--- name: runtime-diagnosis description: Use when kaku crashes, hangs, or behaves unexpectedly at runtime. --- ## Evidence Collection 1. Run `kaku doctor` and capture full output 2. Last 50 lines of `~/.local/share/kaku/logs/` 3. Plugin state: `kaku --list-plugins` ## Decision Matrix | Symptom | First Check | |---|---| | Crash on startup | doctor output → Lua syntax error | | Rendering glitch | GPU backend / terminal capability | | Config not applied | Config path + schema version | ## Output Format Root cause / Blast radius / Fix steps / Verification command
Keep descriptions short; each Skill consumes your context space. Every enabled Skill's description stays in context. The optimization gap is significant:
yaml# Inefficient (~45 tokens) description: | This skill helps you review code changes in Rust projects. It checks for common issues like unsafe code, error handling... Use this when you want to ensure code quality before merging. # Efficient (~9 tokens) description: Use for PR reviews with focus on correctness.
Another important strategy is using disable-auto-invoke:
Skills Anti-patterns
description: help with backend (any backend work could trigger it, haha)5. Tool Design: How to Make Claude Choose Less Wrong
As I used it more, I realized that tools for Claude and APIs for humans are not the same thing. APIs for humans often pursue completeness of features, but for agents, the focus is not on how complete the functionality is, but on making it easier to use correctly.
Good Tools vs Bad Tools

A few practical design principles:
github_pr_, jira_issue_response_format: concise / detailed for large responseslist_all_* for the model to filter itselfLessons from Claude Code Internal Tool Evolution

I found this evolution of the Claude Code team's internal tools quite interesting. For scenarios where they needed to stop mid-task and ask the user, they tried three approaches:
question parameter to an existing tool (e.g., Bash), letting Claude ask questions while calling the tool. Result: Claude mostly ignored this parameter and kept running without stopping to ask.AskUserQuestion tool. For Claude to ask a question, it must explicitly call this tool; calling it triggers a pause with no ambiguity. The effect was significantly better than the first two versions.The image below explains why the third version is clearly more stable:

The left side (free-form markdown output) is too loose—model format is arbitrary, outer parsing is fragile; the right side (ExitPlanTool parameters) is too rigid—by the time the exit plan phase is reached, it's too late to ask; the AskUserQuestion independent tool sits in the middle, structured and callable at any time, making it the most stable design of the three.
Simply put, if you want Claude to stop and ask a question, just give it a dedicated tool. Adding a flag or agreeing on an output format often gets skipped over by Claude.
Evolution of the Todo Tool

Early on, the TodoWrite tool + reminders every 5 rounds were used to make Claude remember tasks. As models got stronger, this tool became a limitation—Todo reminders made Claude think it must strictly follow them, unable to flexibly modify plans. An interesting lesson: the constraint was added because the model wasn't strong enough; once the model got stronger, it became a shackle. Worth revisiting periodically to check if the constraints you added earlier are still valid.
Evolution of the search tool: Initially used RAG vector databases. While fast, they required indexing and were fragile across environments. Most importantly, Claude didn't like using them. Switching to a Grep tool for Claude to search itself yielded significant improvement. Later, a side benefit was discovered: Claude reads Skill files, which reference other files; the model recursively reads them, discovering information on demand without needing to pre-load everything. This pattern was later called "progressive disclosure."
When not to add more Tools:
6. Hooks: Forcefully Insert Your Own Logic Before and After Claude Executes Actions
Hooks are easily mistaken for "auto-run scripts," but from my experience, they are more about taking things that cannot be left to Claude's improvisation and pulling them back into deterministic processes.
For example, whether to run formatting, whether protected files can be modified, whether to notify after task completion—don't expect Claude to remember these every time.
Currently Supported Hook Points

Suitable vs Unsuitable for Hooks
Suitable for: Blocking modifications to protected files, auto-formatting/lint/lightweight validation after Edit, injecting dynamic context (Git branch, environment variables) after SessionStart, and pushing notifications upon task completion.
Not suitable for: Complex semantic judgments requiring extensive context, long-running business processes, or decisions requiring multi-step reasoning and trade-offs. These should be handled in Skills or Subagents.
json{ "hooks": { "PostToolUse": [ { "matcher": "Edit", "pattern": "*.rs", "hooks": [ { "type": "command", "command": "cargo check 2>&1 | head -30", "statusMessage": "Running cargo check..." } ] } ], "Notification": [ { "type": "command", "command": "osascript -e 'display notification \"Task completed\" with title \"Claude Code\"'" } ] } }
Hooks: The earlier you catch errors, the more time you save

In a session of 100 edits, saving 30-60 seconds each time accumulates to 1-2 hours saved, which is quite significant. Be mindful to limit output length (| head -30) to prevent Hook output from polluting the context.
Hooks + Skills + CLAUDE.md: A Three-Layer Stack
From experience, missing any one of these three layers creates gaps. Relying solely on CLAUDE.md rules, Claude often ignores them; relying only on Hooks lacks the nuance for detailed judgment. Combining all three provides stability.
7. Subagents: Deploy an Independent Claude for a Specific Task
A Subagent is an independent Claude instance dispatched from the main conversation. It has its own context window, uses only the tools you specify, and reports back the results. The core value isn't "parallelism" but "isolation." Tasks like scanning a codebase, running tests, or performing reviews that generate large amounts of output are better handled by a Subagent. The main thread only receives a summary, avoiding pollution from intermediate processes. Claude Code includes built-in Subagents: Explore (read-only codebase scan, runs Haiku to save costs), Plan (planning and research), General-purpose, and custom ones.
Explicit Constraints in Configuration
Another practical detail: Long-running bash commands can be sent to the background with Ctrl+B. Claude will later use the BashOutput tool to check the results without blocking the main thread. The same applies to Subagents; simply tell it to "run in the background."
Common Anti-Patterns
8. Prompt Caching: The Core of Claude Code's Internal Architecture
I haven't seen many tutorials cover this in detail, but it significantly impacts Claude Code's cost structure and many design decisions.
There's a saying in engineering: "Cache Rules Everything Around Me." The same applies to agents. Claude Code's entire architecture is built around Prompt caching. High cache hit rates not only reduce costs but also help create more lenient rate limits. Anthropic even runs alerts on hit rates; if they drop too low, it's declared a SEV.
Prompt Layout Designed for Caching

Prompt caching works based on prefix matching. Content from the start of the request up to each cache_control breakpoint is cached. Therefore, the order here is important:
markdownClaude Code's Prompt Order: 1. System Prompt → Static, locked 2. Tool Definitions → Static, locked 3. Chat History → Dynamic, placed later 4. Current User Input → Last
Common Pitfalls That Break Caching
So, what about dynamic information like the current time? Don't touch the System Prompt. Pass it in the next message instead. Claude Code itself does this: it adds a
Don't Switch Models Mid-Session
Prompt caches are model-specific. If you've already conversed with Opus for 100K tokens and want to ask a simple question, switching to Haiku is actually more expensive than continuing with Opus, because the entire cache must be rebuilt for Haiku. If a switch is truly necessary, use a Subagent for handoff: Opus prepares a "handoff message" for the other model, explaining the task to be completed.
The Actual Implementation of Compaction

The image above shows the execution flow of Compaction (context compression): The left side shows the state when context is nearly full. In the middle, Claude Code initiates a fork call, feeding the complete conversation history to the model with the instruction "Summarize this conversation." This step benefits from caching, costing only 1/10 of the price. On the right, after compression, the original dozens of conversation turns are replaced by a ~20k token summary. The System + Tools remain, along with previously used file references, freeing up space for new turns.
Intuitively, Plan Mode should switch to a read-only toolset, but this would break the cache. The actual implementation is that EnterPlanMode is a tool the model can call itself. When it detects a complex problem, it autonomously enters plan mode. The toolset remains unchanged, so the cache is unaffected.
defer_loading: Lazy Loading of Tools
Claude Code has dozens of MCP tools. Including all of them in every request would be expensive, but removing them mid-session breaks the cache. The solution is to send lightweight stubs containing only the tool name, marked with defer_loading: true. The model "discovers" them via the ToolSearch tool. The full tool schema is only loaded after the model selects it, keeping the cache prefix stable.
9. Validation Loop: No Verifier, No Engineering-Grade Agent
"Claude says it's done" is essentially useless. You need to be able to verify if it was done correctly, roll back if there's an issue, and audit the process. That's what counts.
Levels of Verifiers
Explicitly Define Verification in Prompt, Skill, and CLAUDE.md
markdown## Verification For backend changes: - Run `make test` and `make lint` - For API changes, update contract tests under `tests/contracts/` For UI changes: - Capture before/after screenshots if visual Definition of done: - All tests pass - Lint passes - No TODO left behind unless explicitly tracked
When writing task Prompts or Skills, it's best to clarify the acceptance criteria upfront. Which commands need to run for completion? What to check first on failure? What constitutes a pass based on screenshots and logs? The earlier these are clarified, the smoother things go later.
I have a simple rule of thumb: If you can't clearly articulate "how would Claude know it did this correctly," then the task is probably not suitable for fully automated completion by Claude.
10. The Engineering Significance of High-Frequency Commands
These commands essentially do one thing: proactively manage context, rather than waiting for the system to handle it.
Context Management
bash/context # View token usage structure, investigate MCP and file reading proportions /clear # Clear the session; if the same issue requires correction more than twice, start over /compact # Compress while retaining key points, used with Compact Instructions /memory # Confirm which CLAUDE.md files are actually loaded
Capabilities and Governance

bash/mcp # Manage MCP connections, check token costs, disconnect idle servers /hooks # Manage hooks, the control plane entry point /permissions # View or update the permission whitelist /sandbox # Configure sandbox isolation, essential for high-automation scenarios /model # Switch models: Opus for deep reasoning, Sonnet for general use, Haiku for quick exploration
Session Continuity and Parallelism
bashclaude --continue # Resume the most recent session in the current directory, continue the next day claude --resume # Open a selector to resume a historical session claude --continue --fork # Fork from an existing session, same starting point different approaches claude --worktree # Create an isolated git worktree claude -p "prompt" # Non-interactive mode, integrate with CI / pre-commit / scripts claude -p --output-format json # Structured output, easy for script consumption
A few uncommon but useful commands
/simplify: Perform a three-dimensional check on code you've just modified: code reuse, quality, and efficiency. Fix issues directly. Great for running immediately after modifying a piece of logic, replacing manual review.
/rewind: Not "undo", but return to a certain session checkpoint and re-summarize. Suitable for: Claude has been exploring along the wrong path for too long; you want to keep the consensus from the first half but discard the failed second half.
/btw: Quickly ask a side question without interrupting the main task. Suitable for single-round side queries like "what's the difference between these two commands". Not suitable for questions that require reading the repository or calling tools.
claude -p --output-format stream-json: Real-time JSON event stream, suitable for long task monitoring, incremental processing, streaming integration into your own tools.
/insight: Have Claude analyze the current session and extract content worth documenting in CLAUDE.md. Usage: run it after a session has progressed for a while; it will point out blind spots like "this convention has been mentioned repeatedly but hasn't been written into the contract". It's a good way to iteratively optimize CLAUDE.md.
Double-tap ESC to backtrack: Press ESC twice to return to the previous input for re-editing, no need to retype. If Claude goes off track or your last statement wasn't clear, double-tap ESC, modify, and resend. Much more convenient than starting a new session.
Conversation history is all local: All session records are stored under ~/.claude/projects/, folder names are named after the project path (slashes become hyphens), each session is a .jsonl file. To find history on a specific topic, directly grep -rl "keyword" ~/.claude/projects/ to locate it, or simply tell Claude "help me search for previous discussions about X", and it will look it up itself.
11. How to Write a Good CLAUDE.md
In my opinion, CLAUDE.md is more like a collaboration contract between you and Claude. It's not a team document, nor a knowledge base. It should only contain things that must hold true for every session.
My own suggestion is actually quite simple: you can start with nothing at all. Use it first, and when you find yourself repeating the same thing over and over, add it in. Adding is also simple: typing # can append the current conversation content directly into CLAUDE.md, or you can just tell Claude "add this to the project's CLAUDE.md", and it will know which file to modify.

What to include
What NOT to include
High-quality template
markdown# Project Contract ## Build And Test - Install: `pnpm install` - Dev: `pnpm dev` - Test: `pnpm test` - Typecheck: `pnpm typecheck` - Lint: `pnpm lint` ## Architecture Boundaries - HTTP handlers live in `src/http/handlers/` - Domain logic lives in `src/domain/` - Do not put persistence logic in handlers - Shared types live in `src/contracts/` ## Coding Conventions - Prefer pure functions in domain layer - Do not introduce new global state without explicit justification - Reuse existing error types from `src/errors/` ## Safety Rails ## NEVER - Modify `.env`, lockfiles, or CI secrets without explicit approval - Remove feature flags without searching all call sites - Commit without running tests ## ALWAYS - Show diff before committing - Update CHANGELOG for user-facing changes ## Verification - Backend changes: `make test` + `make lint` - API changes: update contract tests under `tests/contracts/` - UI changes: capture before/after screenshots ## Compact Instructions Preserve: 1. Architecture decisions (NEVER summarize) 2. Modified files and key changes 3. Current verification status (pass/fail commands) 4. Open risks, TODOs, rollback notes
Using it is actually not complicated: put things that need to be known every time in CLAUDE.md, things that only apply to certain files in rules, and things only needed for certain types of tasks in Skills.
Let Claude maintain its own CLAUDE.md
One of my favorite tricks: every time you correct Claude's mistake, have it update CLAUDE.md:
"Update your CLAUDE.md so you don't make that mistake again."
Claude is actually quite useful when adding these rules for itself. Over time, it does make the same mistakes less and less. However, you should also review it periodically; over time, some entries will gradually become outdated. The restrictions that were useful initially may no longer be suitable. There's a more systematic approach to this in Section 14 later.
12. New experiences from my own tinkering recently
During the Spring Festival holiday, I used Claude Code to create an open-source terminal project Kaku, with Rust + Lua at its core, also incorporating some AI capabilities. Mixed languages plus a custom configuration system exposed quite a few typical agent collaboration issues during actual tinkering. Let me share a few experiences that were particularly helpful to me.
Environment transparency is more important than you think
Claude Code calls the real shell, git, package manager, and local configuration. If any layer is opaque, it has to start guessing; once it starts guessing about the environment, reliability usually drops quickly. This isn't just a Claude Code problem; many agents are the same.
So I quickly added a doctor command in the terminal to collect environment status, dependencies, and configuration in a unified way, outputting a structured health report. Having Claude Code run doctor before starting work indeed saves many "starting work without understanding the environment" problems.
I also found that if the CLI itself has semantically clear subcommands like init, config, reset, Claude Code works much more stably, much more reliable than letting it guess how configuration files are organized. First stabilize the state, then expose editing entry points. If you reverse the order, things easily get messy.
Hooks practice for mixed-language projects
Two languages, two sets of checks, it's quite suitable to use Hooks triggered by file type:
json{ "hooks": { "PostToolUse": [ { "matcher": "Edit", "pattern": "*.rs", "hooks": [{ "type": "command", "command": "cargo check 2>&1 | head -30", "statusMessage": "Checking Rust..." }] }, { "matcher": "Edit", "pattern": "*.lua", "hooks": [{ "type": "command", "command": "luajit -b $FILE /dev/null 2>&1 | head -10", "statusMessage": "Checking Lua syntax..." }] } ] } }
Knowing immediately after each edit whether there are compilation errors is much more comfortable than "running a bunch of things only to find it failed from the start".
Complete engineering layout reference
If anyone wants to configure a relatively complete Claude Code engineering layout for their project, you can refer to this structure. You don't need to do everything; tailor it as needed:
plaintextProject/ ├── CLAUDE.md ├── .claude/ │ ├── rules/ │ │ ├── core.md │ │ ├── config.md │ │ └── release.md │ ├── skills/ │ │ ├── runtime-diagnosis/ # Unified collection of logs, status, and dependencies │ │ ├── config-migration/ # Configuration migration rollback and contamination prevention │ │ ├── release-check/ # Pre-release validation, smoke test │ │ └── incident-triage/ # Online incident triage │ ├── agents/ │ │ ├── reviewer.md │ │ └── explorer.md │ └── settings.json └── docs/ └── ai/ ├── architecture.md └── release-runbook.md
Global constraints (CLAUDE.md), path constraints (rules), workflows (skills), and architectural details are fully decoupled, significantly improving the execution stability of Claude Code. If you maintain multiple projects simultaneously, you can place a stable personal baseline in ~/.claude/ and project-specific differences in the project-level .claude/, distributing them via sync scripts to avoid cross-project contamination.
13. Common Anti-patterns

14. Configuration Health Check
Based on the six-layer framework in the article, I have organized this check into an open-source Skill project tw93/claude-health, which allows you to check the current state of your Claude Code configuration with one click.
npx skills add tw93/claude-health
After installation, run /health in any session, and it will automatically identify project complexity, run checks on CLAUDE.md, rules, skills, hooks, allowedTools, and actual behavior patterns, and output a priority report: needs immediate fixing / structural issues / can be done gradually.
If you want to know how far your configuration is from these principles after reading this article, running /health is the fastest way.
15. Conclusion
Using Claude Code typically goes through three stages:

In the third stage, the focus subtly shifts from "how to use this feature" to "how to make the agent run autonomously under constraints," and these two things feel quite different.
There is a question worth pondering: if you cannot clearly articulate "what counts as done" for a task, it is likely not suitable to hand it directly to Claude for autonomous completion. Without a validation standard, no matter how smart Claude is, it cannot produce the correct answer.
These are some summaries from half a year of tinkering. There is certainly much more to uncover. If you have tips for using it more effectively, feel free to share them with me.