A Deep Dive into Claude Code (Part 2): Code Scaffolding and Core Logic Mechanisms Link to heading
Introduction: In “A Deep Dive into Claude Code (Part 1): Product Form and Technical Architecture Evolution”, we examined the React rendering engine, KAIROS persistence backend, and the core context explosion-proofing mechanism of Claude Code, the “terminal impersonator”.
Next, we will delve into its approximately 330 underlying TypeScript modules to explore the Core Logic and Control Mechanisms that enable the large model to operate with both freedom and discipline within the terminal. This article will reveal how it achieves a “production-grade” terminal agent through an extremely defensive Tool system.
1. Code Architecture: A Domain-Driven Sandbox World Link to heading
Claude Code features over 60 built-in tools and nearly 100 slash commands. It is less of a prompt wrapper and more of a Virtual Machine (VM) sandbox designed for large language models.
Within its src/tools/ directory, every Tool strictly adheres to a highly consistent generic interface:
interface Tool<Input, Output, Progress> {
name: string
prompt(): string // 动态挂载的安全规则
inputSchema: ZodSchema<Input> // 用于强类型验证
call(input, context): Promise<ToolResult>
checkPermissions(input): PermissionResult // 执行前权限预检
isConcurrencySafe(input): boolean // 并发锁,判定它能否并行执行
// ...以及用于终端 React 渲染的 4 个 render 方法
}
1.1 isConcurrencySafe: The Large Model’s Concurrent Execution Engine
Link to heading
Large models are not single-core machines that execute code linearly.
If a large model issues commands to read A.ts, B.ts, and overwrite C.ts in a single turn, Claude Code’s underlying executor automatically groups and sorts them:
- It places all
isConcurrencySafe=trueread-only operations (likeFileReadTool,GlobTool,GrepTool) into the same micro-batch and executes them instantly with a maximum concurrency of 10 (runConcurrently). - When it’s time for write operations with destructive side-effects (like
BashToolorFileWriteTool), it switches back torunSeriallyfor strict, queued execution.
This design significantly eliminates long-tail latency in terminal responses.
1.2 FileEditTool Instead of Overwriting: Surgical-Precision File Replacement
Link to heading
For code files that are tens of kilobytes, traditional agents tend to overwrite the entire file, which often leads to the accidental deletion of existing code structures.
Claude Code has a built-in precision surgical replacement mechanism (FileEditTool). The large model only needs to provide old string and new string, and the system can accurately find the specific section and perform a precise replacement.
To prevent regex matching errors or out-of-memory (OOM) issues, it even sets a 1 GiB memory limit for single-file modifications and integrates a Git-driven file diff feature by default (gitDiff()) to provide atomic rollback capabilities for human users.
2. Core Design Logic Mechanisms Link to heading
Beyond basic code reading and writing capabilities, Claude Code has built several robust defensive walls at the design level to survive in a developer’s environment.
2.1 The Permission System: A Five-Layer Security Control Network Link to heading
What if the large model tries to run rm -rf? Claude Code’s security mechanism is not based on simple keyword regex.
It employs a high-priority, extremely fine-grained permission pipeline (checkPermissions()):
- Default Mode (
ask): Any destructive command immediately triggers aAskUserQuestionToolhard interruption (Human in the loop), prompting the user in the terminal to choose whether to allow, block, or allow for the entire session. acceptEditsMode: Code modifications are automatically permitted, while only Bash operations are intercepted.- Dangerous Pattern Detection: If a user accidentally provides an extremely dangerous global whitelist entry, such as
python:*, the system automatically identifies this high-risk regex for “arbitrary code execution” and forcibly blocks it to prevent privilege escalation vulnerabilities.
2.2 BashTool: An Executor with a Safety Shield
Link to heading
As the most dangerous and powerful tool, BashTool comes with extremely fine-grained configurations:
- Hard Output Limit (30K chars limit): When the large model runs a build script that generates frantic errors, once its standard output (STDOUT) exceeds 30,000 characters, the excess content is directly written to a ghost folder at
.claude/tool-results. The large model only receives a condensed summary and a file path reference, completely avoiding fatal token overload. - Automatic Background Detachment: When it runs an infinite loop or a persistent service for more than 15 seconds, the engine automatically detaches the process, returns control to the conversation flow, and silently monitors the output in the background.
2.3 Multi-Agent Swarm: Worktree Isolation and Derived Networks Link to heading
Finally, this is the most stunning underlying logic of Claude Code: AgentTool sub-agent derivation.
What happens when a large model runs out of cognitive capacity while refactoring a project?
Through AgentTool, Claude Code can initiate a complete forked development (Sub-Agent Spawning) right before your eyes:
- Isolation Modes: It even automatically pulls a separate Git branch mirror (Worktree) of the current codebase and throws the derived sub-agent into this isolated environment for frantic trial and error!
- Namespacing and Communication (Named Addressing): The main agent can name its clones (e.g.,
test-runner). After a clone successfully passes complex unit tests and writes the code on this isolated branch, the system then merges this correct code back into the main branch (merge). - Cost and Complexity Reduction: The main task is assigned to the most capable but also most expensive
Opus, while the derived testing script agents, which handle the grunt work, can be forced to switch to a cheaperHaikumodel, truly achieving elastic scheduling of intelligent agents.
Summary: The Fundamental Form of Next-Generation Developer Tools Link to heading
In this two-part reverse-engineering chronicle, we have unveiled the mystery of Claude Code. If large models are nuclear reactors, then the 330 underlying libraries written by Anthropic are the extremely thick anti-radiation concrete walls and control rods.
A true production-grade agent tool cannot be solved by merely “a very long prompt.” Its barriers to entry lie in the double-buffered terminal React rendering engine hand-coded in TypeScript, in its extremely meticulous token budget calculations and micro-compression, and even more so in its almost sci-fi “sub-agent swarm running in isolation based on Git Worktree.”
Understanding these aspects is the “official answer” we should be copying when building future AI-native applications.
(End of series)