Analyze and apply architectural patterns from Claude Code's system design for building AI agent systems
triggers
["how does Claude Code architecture work","show me Claude Code design patterns","apply Claude Code safety principles","implement agent loop like Claude Code","use Claude Code permission system design","analyze AI agent architecture patterns","design agent system with Claude Code principles","implement defense in depth for AI agents"]
This skill provides expertise in understanding and applying the architectural patterns, design principles, and implementation strategies documented in the VILA-Lab "Dive into Claude Code" analysis — a comprehensive study of Claude Code v2.1.88 (~512K lines of TypeScript across 1,884 files).
What This Project Provides
The Dive into Claude Code project is a systematic analysis that reveals:
Architectural blueprint: How Claude Code structures its 98.4% deterministic infrastructure around 1.6% AI decision logic
# Clone the repository
git clone https://github.com/VILA-Lab/Dive-into-Claude-Code.git
cd Dive-into-Claude-Code
# Read the paper (PDF in repo or arXiv)
open paper/Dive_into_Claude_Code.pdf
# or visit https://arxiv.org/abs/2604.14228
Core Architecture Patterns
The 98/2 Split
Claude Code demonstrates that production AI agents are primarily infrastructure:
1.6%: AI decision logic (LLM reasoning, tool selection)
// Run sequentially, cheapest-firstasyncfunctioncompactIfNeeded(context: AssembledContext,
tokenBudget: number): Promise<CompactedContext> {
let current = context;
const currentTokens = estimateTokens(current);
if (currentTokens <= tokenBudget) {
return current;
}
// Stage 1: Budget Reduction (remove low-priority items)
current = awaitbudgetReduction(current, tokenBudget);
if (estimateTokens(current) <= tokenBudget) return current;
// Stage 2: Snip (truncate long individual messages)
current = awaitsnipLongMessages(current, tokenBudget);
if (estimateTokens(current) <= tokenBudget) return current;
// Stage 3: Microcompact (remove whitespace, comments)
current = awaitmicrocompact(current);
if (estimateTokens(current) <= tokenBudget) return current;
// Stage 4: Context Collapse (merge related messages)
current = awaitcontextCollapse(current);
if (estimateTokens(current) <= tokenBudget) return current;
// Stage 5: Auto-Compact (LLM-based summarization)
current = awaitautoCompact(current, tokenBudget);
return current;
}
Permission System Implementation
Seven Permission Modes (Graduated Trust)
enumPermissionMode {
Plan = "plan", // Show what would happen, no executionDefault = "default", // Ask for every actionAcceptEdits = "acceptEdits", // Auto-approve file edits onlyAuto = "auto", // ML classifier decidesDontAsk = "dontAsk", // Auto-approve in current directoryBypassPermissions = "bypassPermissions", // Trust completelyBubble = "bubble"// Internal: defer to parent
}
interfaceClassifierResult {
safe: boolean;
reasoning: string;
confidence: number;
}
asyncfunctionclassifyToolCall(call: ToolCall): Promise<ClassifierResult> {
// Fast-filter heuristics (avoid LLM call if obviously safe/unsafe)if (isTriviallyReversible(call)) {
return { safe: true, reasoning: 'Read-only operation', confidence: 1.0 };
}
if (isObviouslyDangerous(call)) {
return { safe: false, reasoning: 'Irreversible system modification', confidence: 1.0 };
}
// Chain-of-thought classifierconst prompt = `
Analyze this tool call for safety:
Tool: ${call.tool}
Arguments: ${JSON.stringify(call.args, null, 2)}
Context: ${call.context}
Consider:
1. Is this operation reversible?
2. Does it modify system-critical files?
3. Could it leak sensitive data?
4. Is the scope appropriate for the task?
Think step-by-step, then answer: SAFE or UNSAFE
`;
const response = awaitcallClassifierModel(prompt);
return {
safe: response.includes('SAFE') && !response.includes('UNSAFE'),
reasoning: response,
confidence: extractConfidence(response)
};
}
Security Considerations
Pre-Trust Execution Window (CVE Pattern)
// ANTI-PATTERN: Executing code before trust established// ❌ Vulnerable: Extension runs during initasyncfunctioninitializeWorkspace() {
awaitloadMCPServers(); // Executes server processesawaitrunHooks('WorkspaceInit'); // Runs arbitrary code// Trust dialog appears AFTER extensions already ranawaitpromptForTrust();
}
// ✅ Safe: Defer privileged operations until after trustasyncfunctioninitializeWorkspace() {
awaitpromptForTrust();
// Only after user approval:if (trusted) {
awaitloadMCPServers();
awaitrunHooks('WorkspaceInit');
}
}
Shared Failure Modes in Defense-in-Depth
// WARNING: Multiple safety layers share performance constraintsasyncfunctionanalyzeCommand(command: string): Promise<SecurityAnalysis> {
const subcommands = parseSubcommands(command);
// If command too complex (>50 subcommands), ALL layers degrade:if (subcommands.length > 50) {
// Layer 1: Security analysis skipped (event loop starvation)// Layer 2: Classifier times out// Layer 3: Hooks don't run// Result: Command executes with minimal oversightreturn {
analyzed: false,
reason: 'Command too complex for analysis',
fallbackToPermissionMode: true
};
}
returnawaitfullSecurityAnalysis(command);
}
Troubleshooting
Context Overflow Despite Compaction
// Check compaction effectivenessasyncfunctiondebugContextOverflow(context: AssembledContext) {
console.log('Token breakdown:');
console.log(' System prompt:', estimateTokens(context.systemPrompt));
console.log(' Conversation:', estimateTokens(context.messages));
console.log(' Tools:', estimateTokens(context.tools));
// Check if a single message is too largeconst largeMessages = context.messages.filter(m =>estimateTokens(m.content) > 10000
);
if (largeMessages.length > 0) {
console.log('Large messages detected - consider manual snipping');
}
// Verify compaction stages ranif (!context.compactionMetadata) {
console.log('WARNING: Compaction metadata missing - pipeline may not have run');
}
}
Permission Denied Despite Allow Rules
// Debug deny-first rule resolutionfunctiondebugPermissionDenial(call: ToolCall, rules: PermissionRule[]) {
const matchingRules = rules.filter(r =>matches(r, call));
console.log(`Matching rules for ${call.tool}:`);
matchingRules.forEach(rule => {
console.log(` [${rule.decision}] ${rule.scope}:${rule.pattern} (priority: ${rule.priority})`);
});
const denyRule = matchingRules.find(r => r.decision === 'deny');
if (denyRule) {
console.log(`\n❌ DENIED by rule: ${denyRule.pattern}`);
console.log(' Deny-first policy means this overrides all allow rules');
}
}
Subagent Not Inheriting Expected Behavior
// Remember: Subagents are ALWAYS isolatedfunctiondebugSubagentIsolation() {
console.log('Subagent isolation checklist:');
console.log(' ❌ Does NOT inherit parent permissions');
console.log(' ❌ Does NOT see parent conversation history');
console.log(' ❌ Does NOT share parent context');
console.log(' ✅ DOES start at default permission mode');
console.log(' ✅ DOES get fresh tool pool');
console.log('\nIf you need shared context, use Skills instead of Subagents');
}