InkdownInkdown
Start writing

Claude-Code

62 files·4 subfolders

Shared Workspace

Claude-Code
codex

00-overview

Shared from "Claude-Code" on Inkdown

Claude Code Architecture Overview

What is Claude Code?

Claude Code is a terminal-based AI assistant built by Anthropic. It integrates Claude (Anthropic's LLM) directly into your terminal, allowing natural language interaction with your codebase, file system, and shell commands.

Think of it as: A REPL (Read-Eval-Print Loop) where the "input" is natural language, the "eval" is Claude + tools, and the "output" is code changes, explanations, or terminal output.


High-Level Architecture

Plain text
┌─────────────────────────────────────────────────────────────────────────────┐
│                              USER INTERFACE                                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │
│  │   Terminal   │  │    REPL      │  │   Bridge     │  │    SDK/API   │   │
│  │    (TUI)     │  │   (Main)     │  │  (Remote)    │  │  (Headless)  │   │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘   │
└─────────┼─────────────────┼─────────────────┼─────────────────┼───────────┘
          │                 │                 │                 │
          └─────────────────┴────────┬────────┴─────────────────┘
                                       │
                              ┌────────▼────────┐
                              │   CORE ENGINE   │
                              │  ┌───────────┐  │
                              │  │  Query    │  │
                              │  │  Engine   │  │
                              │  └─────┬─────┘  │
                              │        │        │
                              │  ┌─────▼─────┐  │
                              │  │  Tool     │  │
                              │  │  System   │  │
                              │  └─────┬─────┘  │
                              │        │        │
                              │  ┌─────▼─────┐  │
                              │  │   Task    │  │
                              │  │  Manager  │  │
                              │  └───────────┘  │
                              └────────┬────────┘
                                       │
          ┌────────────────────────────┼────────────────────────────┐
          │                            │                            │
   ┌──────▼──────┐           ┌─────────▼──────────┐      ┌──────────▼─────────┐
   │   STATE     │           │     SERVICES       │      │   EXTERNAL       │
   │  ┌────────┐ │           │  ┌──────────────┐  │      │   SYSTEMS        │
   │  │AppState│ │           │  │ MCP Client   │  │      │  ┌──────────┐    │
   │  │ Store  │ │           │  │ (Servers)    │  │      │  │Claude API│    │
   │  └────────┘ │           │  └──────────────┘  │      │  └──────────┘    │
   │  ┌────────┐ │           │  ┌──────────────┐  │      │  ┌──────────┐    │
   │  │ Message│ │           │  │  Analytics   │  │      │  │ GitHub   │    │
   │  │ History│ │           │  └──────────────┘  │      │  └──────────┘    │
   │  └────────┘ │           │  ┌──────────────┐  │      │  ┌──────────┐    │
   └─────────────┘           │  │   LSP        │  │      │  │ File     │    │
                             │  │  (Lang Svcs) │  │      │  │ System   │    │
                             │  └──────────────┘  │      │  └──────────┘    │
                             └──────────────────┘      └──────────────────┘
0000_start_here_index_and_recommended_reading_order.md
0100_project_overview_tech_stack_runtime_modes_and_folder_map.md
0200_startup_flow_entry_points_and_cold_start_sequence.md
0300_codebase_modules_layers_state_models_and_schemas.md
0400_system_architecture_and_design_rationale.md
0500_interactive_repl_request_flow_end_to_end.md
0600_headless_sdk_and_print_mode_request_flow_end_to_end.md
0700_mcp_integration_connection_and_tool_call_flow.md
0800_external_services_sdks_storage_and_local_dependencies.md
0900_environment_variables_settings_feature_flags_and_failure_modes.md
1000_non_obvious_patterns_gotchas_and_debugging_traps.md
1100_full_codebase_file_inventory_grouped_by_directory.md
kimi
00-overview.md
01-entrypoints.md
02-state-management.md
03-query-system.md
04-tools-system.md
05-tasks-system.md
06-ui-components.md
07-bridge-remote.md
08-services.md
09-skills-plugins.md
10-commands.md
11-testing-architecture.md
12-permission-system.md
13-build-system.md
14-ink-internals.md
15-git-internals.md
16-context-compaction.md
17-vim-mode.md
18-mailbox-notifications.md
19-session-persistence.md
20-hooks-system.md
21-error-recovery.md
README.md
qwen
00-overview.md
01-entry-points.md
02-query-engine.md
03-tools-and-tasks.md
04-commands-and-skills.md
05-state-management.md
06-ink-rendering.md
07-bridge-remote.md
08-mcp-services.md
09-services-overview.md
10-multi-agent.md
11-system-prompt-constants.md
12-tool-interface.md
13-memory-system.md
14-buddy-companion.md
15-keybindings.md
16-stop-hooks.md
17-vim-mode.md
18-upstreamproxy.md
19-cost-tracking-history.md
20-contexts-styles-onboarding.md
21-hooks.md
22-screens.md
tweets-explain
claude-code-memory-analysis.md
compact
memory-system
agentic-architecture

Key Architectural Patterns

1. Multi-Modal Entrypoints

Claude Code supports multiple ways of interaction:

  • Interactive TUI (main.tsx): Full terminal UI with React Ink
  • CLI Commands (commands/): Slash commands like /commit, /review
  • Bridge Mode (bridge/): Remote control from claude.ai
  • SDK/Headless (entrypoints/sdk/): Programmatic API access
  • Daemon Mode (daemon/): Background process management
2. Query-Centric Flow

Every interaction follows a Query → Tools → Results → Response cycle:

Plain text
User Input → Query Engine → LLM API → Tool Requests → Tool Execution → Results → LLM → Response
                ↑                                                              │
                └──────────────── Context Window ←─────────────────────────────┘
3. Immutable State with React Sync
  • AppStateStore: Single source of truth (Zustand-style store)
  • useAppState: React hook for subscribing to state slices
  • Message-based: All history stored as immutable messages
4. Tool Architecture

Tools are self-contained units that:

  • Define their own input schema (Zod)
  • Handle their own execution
  • Render their own UI (if needed)
  • Report progress and results
5. Task System

Background work uses a task model:

  • LocalShellTask: Bash command execution
  • LocalAgentTask: Sub-agent spawning
  • RemoteAgentTask: Remote agent coordination

Directory Structure at a Glance

DirectoryPurposeKey Concept
entrypoints/Application entry pointsCLI, SDK, bridge modes
commands/Slash commands (/commit, /diff)Command pattern
tools/AI-invokable tools (Bash, FileEdit, etc.)Tool pattern
tasks/Background task implementationsTask pattern
state/Global state managementStore pattern
components/React/Ink UI componentsComponent architecture
services/External service integrationsService layer
bridge/Remote control & cloud syncBridge pattern
skills/User-defined skillsSkill system
hooks/React hooks for UI logicHook pattern
context/React context providersContext pattern
utils/Utility functionsUtilities
types/TypeScript type definitionsType system

Data Flow Deep Dive

Message Flow
TypeScript
// 1. User creates a message
const userMessage: UserMessage = {
  type: 'user',
  content: [{ type: 'text', text: 'Fix the bug' }],
  uuid: generateUUID(),
}

// 2. Query Engine processes it
const response = await queryEngine.submitMessage(userMessage)

// 3. LLM may request tool uses
const toolUse: ToolUseBlock = {
  type: 'tool_use',
  name: 'BashTool',
  input: { command: 'grep -r "bug" src/' },
}

// 4. Tool executes and returns result
const toolResult: ToolResultBlock = {
  type: 'tool_result',
  tool_use_id: toolUse.id,
  content: 'Found bug in src/index.ts',
}

// 5. LLM generates final response
const assistantMessage: AssistantMessage = {
  type: 'assistant',
  content: [{ type: 'text', text: 'I found the bug...' }],
}
State Updates
TypeScript
// State updates are immutable transformations
setAppState(prev => ({
  ...prev,
  messages: [...prev.messages, newMessage],
  usage: accumulateUsage(prev.usage, newUsage),
}))

Key Abstractions for Junior Engineers

1. The "Turn" Concept

A "turn" is one complete back-and-forth:

  • User sends message
  • Claude thinks (may use tools)
  • Claude responds
  • State is updated

Think of it like a chess turn: user moves, Claude responds.

2. Context Window Management

The context window is precious real estate. Claude Code uses:

  • Compaction: Summarizes old messages when limit approaches
  • Auto-compact: Automatic summarization at thresholds
  • Snip: Truncates history for long sessions
3. Permission System

Tools can be dangerous (bash, file writes). The system:

  • Classifies tools by risk level
  • Shows permission dialogs for dangerous operations
  • Supports "Auto Mode" (trust Claude) and "Bypass" modes
4. The Bridge Pattern

Bridge mode connects your local terminal to claude.ai:

  • Local terminal runs the code
  • Web UI shows the interface
  • Bidirectional sync of state

Technology Stack

LayerTechnology
RuntimeBun (JavaScript/TypeScript)
UI FrameworkReact + Ink (terminal React)
State ManagementCustom store (Zustand-like)
APIAnthropic SDK
BuildBun bundler with dead code elimination
TestingBun test runner
Process ManagementBun spawn, custom task system

Dead Code Elimination (DCE)

Claude Code uses feature() flags for build-time DCE:

TypeScript
// This code is removed from external builds
const SleepTool = feature('PROACTIVE')
  ? require('./SleepTool.js').SleepTool
  : null

This keeps the binary small by excluding ant-internal features.


Next Steps

Read the detailed architecture docs:

  1. Entrypoints - How the app starts and branches
  2. State Management - How data flows through the app
  3. Query System - How Claude API calls work
  4. Tools System - How tools are defined and executed
  5. Tasks System - Background task management
  6. UI Components - Terminal UI architecture
  7. Bridge & Remote - Cloud connectivity
  8. Services - External integrations
  9. Skills & Plugins - Extension system
  10. Commands - Slash command system

Glossary

  • REPL: Read-Eval-Print Loop (interactive shell)
  • TUI: Terminal User Interface
  • MCP: Model Context Protocol (external tool integration)
  • LSP: Language Server Protocol
  • DCE: Dead Code Elimination
  • Turn: One user-Claude interaction cycle
  • Context Window: LLM's memory limit (varies by model)
  • Bridge: Remote control connection to claude.ai
  • Agent: Autonomous AI worker spawned for specific tasks