| name | how-claude-code-works-analysis |
| description | Expert guidance on understanding Claude Code internals, architecture patterns, agent loops, context engineering, and AI coding agent design principles |
| triggers | ["how does Claude Code work internally","explain Claude Code architecture","understand AI agent design patterns","implement AI coding agent features","Claude Code source code analysis","build coding agent like Claude","context compression strategies","AI agent security and permissions"] |
How Claude Code Works Analysis
Skill by ara.so — Claude Code Skills collection.
Expert knowledge of Claude Code's internal architecture, based on deep analysis of its 512,000+ line TypeScript codebase. This skill helps you understand production-grade AI coding agent design, implement similar features, and leverage Claude Code's advanced capabilities.
What This Project Provides
how-claude-code-works is a comprehensive documentation project analyzing Claude Code's source code:
- 15 specialized chapters covering architecture, agent loops, context engineering, tools, permissions, multi-agent systems, and UX
- Interactive documentation site with diagrams and code references
- Companion implementation project (claude-code-from-scratch) with working TypeScript/Python examples
- Production-grade patterns validated by millions of daily users
Key Architecture Concepts
Core Agent Loop
The dual-layer architecture separates concerns:
class QueryEngine {
async query(userMessage: string) {
}
}
class StreamingToolExecutor {
}
7 Continuation Sites for fault recovery:
- ContextLengthExceeded → compress and retry
- MaxTokensReached → upgrade from 4K to 64K limit
- ToolError → inject error, continue loop
- UserInterrupt → save state, allow resume
- RateLimitHit → exponential backoff
- ValidationFailure → rollback, re-plan
- CompactionNeeded → trigger compression pipeline
4-Level Context Compression Pipeline
When approaching context limits, execute progressively:
async function trimCompaction(messages: Message[]): Promise<Message[]> {
return messages.map(msg => {
if (msg.role === 'assistant' && msg.toolResults) {
return truncateToolResults(msg, 1000);
}
return msg;
});
}
async function dedupeCompaction(messages: Message[]): Promise<Message[]> {
const seen = new Set<string>();
return messages.filter(msg => {
const hash = hashContent(msg);
if (seen.has(hash)) return false;
seen.add(hash);
return true;
});
}
async (): <[]> {
}
(): <[]> {
summary = subAgent.(messages);
[summary, ...()];
}
Critical: After compression, automatically restore:
- Last 5 edited files (full content)
- Active skills that were in use
- Current working context
Tool System Architecture
All 66+ tools follow unified interface:
interface Tool {
name: string;
description: string;
parameters: ZodSchema;
execute(params: z.infer<parameters>): Promise<ToolResult>;
readonly: boolean;
requiresApproval: boolean;
tokenBudget?: number;
}
const readFileTool: Tool = {
name: 'read_file',
readonly: true,
requiresApproval: false,
async execute({ path }: { path: string }) {
const content = await fs.readFile(path, 'utf-8');
if (content.length > 100_000) {
await fs.writeFile(`/tmp/${hash(path)}`, content);
return {
: content.(, ),
: ,
:
};
}
{ content };
}
};
5-Layer Security Model
Defense in depth for dangerous operations:
enum PermissionMode {
Full,
Limited,
ReadOnly,
Ask
}
const rules = {
allowPatterns: [/^git status$/, /^npm test$/],
denyPatterns: [/rm -rf \//, /sudo/, /curl .* \| bash/]
};
async function analyzeBashCommand(cmd: string): Promise<SecurityRisk[]> {
const ast = parseShellWithTreeSitter(cmd);
return [
checkCommandInjection(ast),
checkEnvVarLeakage(ast),
checkFileSystemRisk(ast),
checkNetworkAccess(ast),
checkPrivilegeEscalation(ast),
].filter(risk => risk.severity >= 'medium');
}
async function confirmDangerousOperation(): <> {
();
(operation, risks);
}
(): <> {
customRules = ();
( hook customRules) {
result = hook.(request);
(result.) result;
(result.) {
request. = result.;
}
}
{ : };
}
Multi-Agent Coordination
Three patterns supported:
async function delegateToSubAgent(task: string) {
const subAgent = await QueryEngine.createSubAgent({
task,
worktree: await git.createWorktree(),
inheritContext: true
});
const result = await subAgent.run();
await git.mergeWorktree(subAgent.worktree);
return result;
}
class CoordinatorAgent extends QueryEngine {
async execute(tool: Tool) {
if (!tool.name.startsWith('delegate_')) {
throw new Error('Coordinators must delegate all work');
}
return super.execute(tool);
}
}
class {
() {
messageBus.(toAgent, {
: .,
: message,
: .()
});
}
(): <[]> {
messageBus.(.);
}
}
Configuration via CLAUDE.md
Place in project root to customize behavior:
# Project Context
This is a TypeScript monorepo using Bun and React.
## Custom Tools
### run_integration_tests
Runs full test suite with real API calls (takes ~5min).
Requires: API_KEY environment variable set.
## Permission Rules
- ALLOW: npm test, npm run build
- DENY: npm publish (manual only)
- REQUIRE_CONFIRM: database migrations
## Skills Priority
1. Use Zod for all validation
2. Prefer Bun APIs over Node.js when available
3. Always run formatter before commit
## Memory
REMEMBER: API rate limit is 100 req/min. Batch operations when possible.
Common Patterns
Streaming with Tool Pre-execution
async function streamingQuery(userMessage: string) {
const stream = await claude.messages.create({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: userMessage }],
tools: allTools,
stream: true
});
const toolExecutor = new StreamingToolExecutor();
for await (const chunk of stream) {
process.stdout.write(chunk.delta.text || '');
if (chunk.delta.type === 'tool_use') {
toolExecutor.queue(chunk.delta);
}
}
const results = await toolExecutor.waitAll();
return results;
}
Context Budget Management
interface ContextBudget {
total: 200_000;
allocation: {
systemPrompt: 5000,
claudeMd: 3000,
gitStatus: 1000,
skills: 15000,
conversation: 176000
};
}
async function buildContext(budget: ContextBudget): Promise<Message[]> {
const messages: Message[] = [];
messages.push(await loadSystemPrompt());
const claudeMd = await loadClaudeMd();
if (claudeMd) messages.push(claudeMd);
const activeSkills = await matchSkills(conversationHistory);
messages.push(...activeSkills.(, budget..));
conversation = conversationHistory;
((conversation) > budget..) {
conversation = (conversation);
}
messages.(...conversation);
messages;
}
Edit-Before-Read Enforcement
class EditFileTool implements Tool {
async execute({ path, edits }: EditParams) {
const current = await fs.readFile(path, 'utf-8');
for (const edit of edits) {
const occurrences = countOccurrences(current, edit.search);
if (occurrences === 0) {
throw new Error(`Search string not found: ${edit.search}`);
}
if (occurrences > 1) {
throw new Error(
`Search string not unique (found ${occurrences} times): ${edit.search}`
);
}
}
let result = current;
for (const edit of edits) {
result = result.replace(edit.search, edit.replace);
}
await fs.writeFile(path, result);
return { : , : edits. };
}
}
Advanced Usage
Custom Hook Implementation
export default {
name: 'prevent-friday-deploys',
event: 'permission:shell',
async handle(request: PermissionRequest): Promise<HookResult> {
const isFriday = new Date().getDay() === 5;
const isDeploy = request.command.includes('deploy');
if (isFriday && isDeploy) {
return {
deny: true,
reason: 'No deploys on Friday (team policy)',
suggestion: 'Schedule for Monday or run with --force-friday flag'
};
}
return { allow: true };
}
};
Prompt Caching Strategy
const systemPrompt = {
role: 'system',
content: [
{
type: 'text',
text: await loadSystemPrompt(),
cache_control: { type: 'ephemeral' }
}
]
};
const claudeMd = {
role: 'system',
content: [
{
type: 'text',
text: await fs.readFile('CLAUDE.md'),
cache_control: { type: 'ephemeral' }
}
]
};
function detectCacheBreak(oldMessages: Message[], newMessages: Message[]) {
const oldCached = oldMessages.filter(m => m.cache_control);
const newCached = newMessages.filter(m => m.cache_control);
return !isEqual(oldCached, newCached);
}
Troubleshooting
Context Length Exceeded
const debug = {
async diagnoseCompression() {
console.log('Level 1 (trim):', await estimateTokenSavings(trimCompaction));
console.log('Level 2 (dedupe):', await estimateTokenSavings(dedupeCompaction));
console.log('Level 3 (fold):', await estimateTokenSavings(foldCompaction));
console.log('Level 4 (summarize):', await estimateTokenSavings(summarizeCompaction));
}
};
await forceCompaction(messages, { target: 150_000 });
Tools Not Executing
const registeredTools = queryEngine.getTools();
console.log('Registered:', registeredTools.map(t => t.name));
const permissionMode = await getPermissionMode();
console.log('Mode:', permissionMode);
if (permissionMode === PermissionMode.ReadOnly) {
await setPermissionMode(PermissionMode.Ask);
}
Memory Not Persisting
const memories = await memorySystem.search('project structure');
console.log('Found memories:', memories.length);
await memorySystem.extract({
type: 'project',
content: 'This is a React app using Vite',
importance: 0.9
});
Slow Startup
await Promise.all([
loadSystemPrompt(),
loadClaudeMd(),
initializeGit(),
connectMCPServers(),
loadSkills(),
]);
Resources
- Documentation Site: https://windy3f3f3f3f.github.io/how-claude-code-works/
- Source Analysis: https://github.com/Windy3f3f3f3f/how-claude-code-works
- Implementation Guide: https://github.com/Windy3f3f3f3f/claude-code-from-scratch
- 15 Deep-Dive Chapters: Architecture, Agent Loop, Context Engineering, Tools, Skills, Memory, Hooks, Multi-Agent, Plan Mode, Editing, Tasks, Permissions, Prompts, UX, Minimal Components
Environment Variables
ANTHROPIC_API_KEY=sk-ant-...
CLAUDE_MODEL=claude-3-5-sonnet-20241022
DEBUG_AGENT_LOOP=true
DEBUG_COMPRESSION=true
DEBUG_TOOLS=true
This skill enables deep understanding and implementation of production-grade AI coding agent patterns used by millions of developers.