๐Ÿ”ฌ Claude Code Deep Dive

Phรขn tรญch toร n diแป‡n source code bแป‹ leak cแปงa Claude Code โ€” Anthropic's $10B+ flagship AI coding CLI. Chแบฏt lแปc kiแบฟn trรบc, patterns, hidden features, vร  bร i hแปc cho OpenClaw.

๐Ÿ“… 2026-03-31 (Leak date) ๐Ÿ” Nacharium Research Lab ๐Ÿ“ฆ Source: npm sourcemap leak โšก Tech: Bun + React Ink + TypeScript
477K
Lines of TypeScript
1,884
Source Files (.ts/.tsx)
30.6 MB
Total Source Size
40+
Built-in Tools
70+
Slash Commands
๐Ÿ—๏ธ Architecture ๐Ÿ”ง Tool System โŒจ๏ธ Commands ๐Ÿค– Multi-Agent ๐Ÿ”ฎ Hidden Features ๐Ÿ“ System Prompts ๐Ÿง  Memory ๐Ÿ”’ Security โ˜๏ธ Services ๐Ÿ–ฅ๏ธ UI/UX ๐Ÿ“š Skills ๐Ÿ’ก Lessons ๐Ÿ“Š Code Quality
๐Ÿ—๏ธ

Architecture Overview

Core Foundation โ–ผ

Tech Stack

Claude Code lร  mแป™t CLI app ฤ‘ฦฐแปฃc build bแบฑng stack rแบฅt thรบ vแป‹ โ€” khรดng phแบฃi Node.js thรดng thฦฐแปng mร  dรนng Bun runtime (custom fork cแปงa Anthropic) kแบฟt hแปฃp vแป›i React + Ink ฤ‘แปƒ render terminal UI.

โšก Bun Runtime (Custom Fork)

Anthropic fork Bun runtime riรชng, thรชm bun:bundle feature flags cho dead code elimination. Build-time defines nhฦฐ feature('KAIROS') cho phรฉp conditional compilation โ€” branches khรดng active sแบฝ bแป‹ strip khแปi build output.

โš›๏ธ React + Ink

Terminal UI ฤ‘ฦฐแปฃc render bแบฑng React components thรดng qua Ink library. REPL.tsx (879KB!) lร  main screen component โ€” lแป›n nhแบฅt codebase. Toร n bแป™ UI lร  React components: Messages, PromptInput, Stats, VirtualMessageList...

๐Ÿ“ฆ TypeScript + Zod v4

Toร n bแป™ codebase dรนng TypeScript strict mode vแป›i Zod cho schema validation. Tool inputs/outputs ฤ‘แปu ฤ‘ฦฐแปฃc validate qua Zod schemas.

๐Ÿ”ง Commander.js CLI

CLI parsing dรนng Commander.js. Entry point main.tsx (789KB - monolithic bundle) setup Commander program vแป›i 20+ subcommands.

Entry Point โ€” main.tsx (789KB)

File entry point khแป•ng lแป“ lร  mแป™t monolithic bundle. Nรณ khแปŸi tแบกo Commander program, ฤ‘ฤƒng kรฝ tแบฅt cแบฃ subcommands (claude chat, claude agent, etc.), parse CLI args, rแป“i render React Ink app.

main.tsx โ€” CLI setup structure
// Commander.js program setup
const program = new Command()
  .name('claude')
  .version(MACRO.VERSION)
  .option('--model <model>', 'Model to use')
  .option('--permission-mode <mode>', 'Permission mode')
  .option('--tools <preset>', 'Tool preset')
  .option('--add-dir <path>', 'Additional directories')
  .option('--bare', 'Skip auto-discovery')
  // ... 30+ more options

// Main interactive mode renders React Ink app
program.action(async () => {
  await setup(/* ... */)
  const { waitUntilExit } = render(
    <App />,  // React Ink component tree
    { exitOnCtrlC: false }
  )
  await waitUntilExit()
})

Architecture Diagram

graph TB CLI[main.tsx - CLI Entry] --> Setup[setup.ts - Bootstrap] Setup --> REPL[REPL.tsx - Main Screen
879KB React Component] REPL --> QE[query.ts - Query Engine
Agentic Loop] QE --> API[claude.ts - API Layer
126KB] QE --> Tools[Tool System
40+ tools] QE --> Hooks[Hook System
Pre/Post Tool Use] Tools --> BashTool[BashTool
158KB] Tools --> FileEdit[FileEditTool] Tools --> AgentTool[AgentTool
230KB - Sub-agents] Tools --> MCPTools[MCP Tools
119KB client] REPL --> Messages[Message Components] REPL --> PromptInput[PromptInput
349KB] REPL --> Stats[Stats Panel] Setup --> Config[Config System] Setup --> Analytics[GrowthBook Analytics] Setup --> Memory[Memory System
autoDream + memdir] style CLI fill:#1a1e24,stroke:#58a6ff,color:#e6edf3 style REPL fill:#1a1e24,stroke:#bc8cff,color:#e6edf3 style QE fill:#1a1e24,stroke:#3fb950,color:#e6edf3 style AgentTool fill:#1a1e24,stroke:#f85149,color:#e6edf3 style Memory fill:#1a1e24,stroke:#d29922,color:#e6edf3

Build Pipeline

Bun bundler ฤ‘ฦฐแปฃc dรนng vแป›i custom feature() flags tแปซ bun:bundle. Mแป—i feature flag lร  build-time constant โ€” cho phรฉp tree-shaking toร n bแป™ code paths khรดng active. Vรญ dแปฅ:

Feature flags โ€” dead code elimination
import { feature } from 'bun:bundle'

// External build: feature('KAIROS') = false โ†’ entire block stripped
const SleepTool = feature('PROACTIVE') || feature('KAIROS')
  ? require('./tools/SleepTool/SleepTool.js').SleepTool
  : null

// External build: feature('BUDDY') = false โ†’ buddy code eliminated
const buddy = feature('BUDDY')
  ? require('./commands/buddy/index.js').default
  : null
๐Ÿ’ก Insight cho OpenClaw: Feature flag system via build-time constants lร  cแปฑc kแปณ hiแป‡u quแบฃ cho conditional compilation. OpenClaw cรณ thแปƒ รกp dแปฅng pattern tฦฐฦกng tแปฑ ฤ‘แปƒ ship different builds (lite vs full) tแปซ cรนng codebase.

Directory Structure

DirectoryFilesLinesPurpose
utils/564165,026Utility functions โ€” lแป›n nhแบฅt, chแปฉa permissions, messages, config, model, git, etc.
components/38980,166React Ink UI components โ€” Messages, VirtualList, LogSelector, Stats
services/13049,063API layer, MCP, analytics, compact, autoDream, memory extraction
tools/18447,211All 40+ tool implementations
commands/18924,97370+ slash commands
hooks/10417,931React hooks cho state management
bridge/3111,761Bridge mode โ€” remote control via daemon
skills/203,538Skill system โ€” loadSkillsDir, bundledSkills
memdir/81,639Memory directory system โ€” paths, types, scanning
vim/51,358Full Vim mode โ€” motions, operators, text objects
buddy/61,253๐Ÿฅš Hidden Tamagotchi pet system!
coordinator/1276Multi-agent coordinator mode
๐Ÿ”ง

Tool System โ€” 40+ Built-in Tools

184 files ยท 47K lines โ–ผ

Tool Architecture

Mแป—i tool implement interface Tool<Input, Output, Progress> (file Tool.ts โ€” 793 lines). Tools ฤ‘ฦฐแปฃc register qua buildTool() factory function cung cแบฅp defaults fail-closed. Kiแบฟn trรบc rแบฅt mature vแป›i:

  • Zod schema validation cho inputs
  • Permission checking 3 lแป›p: validateInput โ†’ checkPermissions โ†’ hook system
  • Concurrency safety declarations (isConcurrencySafe)
  • Read-only / Destructive annotations cho auto-mode classification
  • Deferred loading via ToolSearch โ€” lazy load tools chแป‰ khi cแบงn
  • Progress reporting โ€” live progress UI while tool runs
  • Interrupt behavior โ€” tool cรณ thแปƒ bแป‹ cancel hay block khi user submits new message
Tool.ts โ€” buildTool() with fail-closed defaults
const TOOL_DEFAULTS = {
  isEnabled: () => true,
  isConcurrencySafe: (_input?) => false,  // assume not safe
  isReadOnly: (_input?) => false,         // assume writes
  isDestructive: (_input?) => false,
  checkPermissions: (input, _ctx?) =>     // defer to general system
    Promise.resolve({ behavior: 'allow', updatedInput: input }),
  toAutoClassifierInput: (_input?) => '', // skip classifier
  userFacingName: (_input?) => '',
}

export function buildTool<D extends AnyToolDef>(def: D): BuiltTool<D> {
  return { ...TOOL_DEFAULTS, userFacingName: () => def.name, ...def }
}

Complete Tool Catalog

ToolTypeNotes
BashToolCore158KB โ€” Shell execution with 103KB security validation! Sandboxing support.
FileReadToolCoreRead files with line ranges, encoding detection
FileEditToolCoreSurgical text edits with old_string/new_string matching
FileWriteToolCoreCreate/overwrite files with auto parent dirs
GlobToolSearchFile pattern search (removed when embedded bfs available)
GrepToolSearchContent search (removed when embedded ugrep available)
AgentToolMulti-Agent230KB! Spawn sub-agents/forks. Most complex tool.
SkillToolExtensionExecute user-defined skills from .claude/skills/
WebFetchToolWebFetch URLs, extract readable content
WebSearchToolWebSearch the web
WebBrowserToolWeb๐Ÿ”ฎ Feature Flag Full browser control
TodoWriteToolTaskTask management (deprecated โ†’ TaskCreate/Get/Update/List)
TaskCreateToolTask v2Create structured tasks
TaskGetToolTask v2Retrieve task details
TaskUpdateToolTask v2Update task status
TaskListToolTask v2List all tasks
TaskStopToolControlStop a running agent/task
TaskOutputToolControlGet agent output
AskUserQuestionToolInteractiveAsk user a question mid-flow
NotebookEditToolJupyterEdit Jupyter notebooks
ExitPlanModeV2ToolPlanExit planning mode
EnterPlanModeToolPlanEnter planning mode
LSPToolIDELanguage Server Protocol integration
ListMcpResourcesToolMCPList MCP server resources
ReadMcpResourceToolMCPRead MCP resources
ToolSearchToolMetaSearch available tools (lazy loading)
ConfigToolConfigant-only Runtime configuration
TungstenToolInternalant-only Internal Anthropic tool
BriefToolKAIROSHidden Brief/summary for KAIROS assistant
SleepToolKAIROSHidden Proactive mode sleep
SendMessageToolMulti-AgentSend message to running agent
SendUserFileToolKAIROSHidden Send files to user
PushNotificationToolKAIROSHidden Push notifications
SubscribePRToolKAIROSHidden GitHub PR webhooks
TeamCreateToolSwarmHidden Create agent teams
TeamDeleteToolSwarmHidden Delete agent teams
REPLToolREPLant-only REPL mode wrapper
PowerShellToolShell142KB โ€” Windows PowerShell support
EnterWorktreeToolGitGit worktree isolation mode
ExitWorktreeToolGitExit worktree
SnipToolContextHidden History snipping for context management
ListPeersToolP2PHidden UDS inbox peer discovery
WorkflowToolWorkflowHidden Workflow script execution
MonitorToolMonitorHidden System monitoring
CronCreate/Delete/ListToolCronHidden Scheduled task management
RemoteTriggerToolRemoteHidden Remote agent triggers
CtxInspectToolDebugHidden Context collapse inspector
TerminalCaptureToolDebugHidden Terminal panel capture
SuggestBackgroundPRToolInternalant-only Background PR suggestions

Permission System (3 layers)

Permission checking rแบฅt sophisticated vแป›i 3 lแป›p defense-in-depth:

Permission flow per tool call
// Layer 1: Tool-level validation
tool.validateInput(input, context)  // structural/semantic checks

// Layer 2: Tool-specific permission check 
tool.checkPermissions(input, context)  // tool's own rules

// Layer 3: General permission system (permissions.ts)
// - Check deny rules (blanket deny by tool name or pattern)
// - Check allowedTools/blockedTools from settings
// - Check auto-mode classifier (yoloClassifier.ts)
// - Prompt user if needed

// Layer 3.5: Hook system (PreToolUse hooks from CLAUDE.md)
// User-defined shell commands that run before tool execution
โš ๏ธ BashTool Security: BashTool alone has 103KB of security validation code (bashSecurity.ts). Includes command parsing, path validation, sed validation, read-only validation, destructive command detection, and sandbox mode.
โŒจ๏ธ

Command System โ€” 70+ Slash Commands

189 files ยท 25K lines โ–ผ

Commands vs Tools

Quan trแปng: Commands โ‰  Tools. Commands lร  slash commands user gรต (/compact, /help), Tools lร  AI-callable functions. Commands can inject prompts, modify state, or render UI โ€” tools execute actions cho AI.

Command Types

  • prompt โ€” Inject content into conversation (e.g., /commit injects git commit prompt)
  • local โ€” Run locally, return result (e.g., /cost shows token usage)
  • local-jsx โ€” Render React component (e.g., /theme shows color picker)

Full Command Catalog

๐Ÿ“‹ Core Commands

/help /clear /compact /cost /exit /status /stats /version /diff /copy /model /effort

๐ŸŽจ Customization

/theme /color /vim /keybindings /output-style /stickers /fast /statusline

๐Ÿ”ง Development

/commit /review /ultrareview /pr_comments /security-review /bughunter /branch /plan

๐Ÿ“ฑ Platform

/desktop /mobile /ide /chrome /terminal-setup /login /logout

๐Ÿง  Memory & Context

/memory /context /files /add-dir /resume /session /rewind /thinkback

๐Ÿ”ฎ Hidden Commands

Hidden /buddy /proactive /assistant /bridge /voice /ultraplan /torch /fork /peers /workflows

Dynamic Skills as Commands

Ngoร i built-in commands, Claude Code load thรชm skills tแปซ 4 nguแป“n:

  1. Skill directories โ€” .claude/skills/ (project) + ~/.claude/skills/ (user)
  2. Plugin skills โ€” From installed plugins
  3. Bundled skills โ€” Ship with CLI
  4. Built-in plugin skills โ€” From enabled built-in plugins
๐Ÿค–

Multi-Agent Orchestration

Coordinator + Fork + Teams โ–ผ

3 Modes of Multi-Agent

๐Ÿ‘” Coordinator Mode

Hidden Feature Full coordinator-worker pattern. Coordinator only gets AgentTool + SendMessageTool + TaskStopTool. Workers execute actual tasks. Coordinator synthesizes results. Massive system prompt (276 lines) teaches the coordinator how to delegate.

๐Ÿ”ฑ Fork Subagent

Hidden Feature Omit subagent_type to fork yourself โ€” inherits full conversation context. Shares prompt cache with parent. Ideal for research/exploration without polluting parent context.

๐Ÿ Agent Swarms (Teams)

Hidden Feature TeamCreateTool + TeamDeleteTool for creating named agent teams. Multiple agents collaborate under a team namespace.

AgentTool (230KB) โ€” The Heart

AgentTool.tsx (230KB) lร  tool phแปฉc tแบกp nhแบฅt toร n codebase. Nรณ handle:

  • Spawning sub-agents with isolated context
  • Fork mode (inherits parent context + cache)
  • Background execution with completion notifications
  • Agent memory snapshots
  • Git worktree isolation mode
  • Remote CCR (Claude Code Remote) execution
  • Agent color management for UI

Coordinator System Prompt (key excerpt)

coordinatorMode.ts โ€” Coordinator identity
// The coordinator gets a massive system prompt teaching it to:
`You are Claude Code, an AI assistant that orchestrates software 
engineering tasks across multiple workers.

## Your Role
- Help the user achieve their goal
- Direct workers to research, implement and verify code changes
- Synthesize results and communicate with the user
- Answer questions directly when possible

## Task Workflow Phases:
| Phase          | Who      | Purpose                    |
|----------------|----------|----------------------------|
| Research       | Workers  | Investigate, find files    |
| Synthesis      | YOU      | Understand, craft specs    |
| Implementation | Workers  | Make changes, commit       |
| Verification   | Workers  | Test changes work          |

**Never delegate understanding.** Don't write "based on your 
findings, fix the bug" โ€” synthesize yourself first.`
๐Ÿ’ก Key Insight cho OpenClaw: Claude Code's coordinator pattern of "Never delegate understanding" is brilliant. The coordinator must prove it understood findings before sending implementation specs. This prevents lazy delegation and ensures quality. OpenClaw should adopt this pattern for multi-agent workflows.

Worker Communication

Workers communicate via <task-notification> XML injected as user-role messages:

Task notification format
<task-notification>
  <task-id>agent-a1b</task-id>
  <status>completed</status>
  <summary>Agent "Investigate auth bug" completed</summary>
  <result>Found null pointer in src/auth/validate.ts:42...</result>
  <usage>
    <total_tokens>15234</total_tokens>
    <tool_uses>8</tool_uses>
    <duration_ms>45000</duration_ms>
  </usage>
</task-notification>
๐Ÿ”ฎ

Hidden & Unreleased Features

๐Ÿฅš Easter Eggs Inside โ–ผ

๐Ÿฃ BUDDY โ€” Tamagotchi Pet System

Feature Flag: BUDDY ฤรขy lร  feature thรบ vแป‹ nhแบฅt โ€” mแป™t hแป‡ thแป‘ng Tamagotchi/Gacha pet sแป‘ng bรชn cแบกnh input box cแปงa Claude Code!

๐ŸŽฒ Gacha Mechanics

18 species: duck, goose, blob, cat, dragon, octopus, owl, penguin, turtle, snail, ghost, axolotl, capybara, cactus, robot, rabbit, mushroom, chonk

5 rarities: Common (60%), Uncommon (25%), Rare (10%), Epic (4%), Legendary (1%!)

Eyes: ยท โœฆ ร— โ—‰ @ ยฐ
Hats: none, crown, tophat, propeller, halo, wizard, beanie, tinyduck

๐Ÿ“Š Stats System

5 stats: DEBUGGING, PATIENCE, CHAOS, WISDOM, SNARK

Each companion has one peak stat (high) and one dump stat (low). Rarity determines the floor:
Common: 5, Uncommon: 15, Rare: 25, Epic: 35, Legendary: 50

Shiny: 1% chance โ€” extremely rare variant!

buddy/types.ts โ€” Rarity system
export const RARITY_WEIGHTS = {
  common: 60,
  uncommon: 25,
  rare: 10,
  epic: 4,
  legendary: 1,  // 1% chance!
} as const

export const RARITY_STARS = {
  common: 'โ˜…',
  uncommon: 'โ˜…โ˜…',
  rare: 'โ˜…โ˜…โ˜…',
  epic: 'โ˜…โ˜…โ˜…โ˜…',
  legendary: 'โ˜…โ˜…โ˜…โ˜…โ˜…',
} as const

Companions are deterministically generated from hash(userId) using Mulberry32 PRNG. ASCII art sprites animate with 3 frames per species. The companion "sits beside the user's input box and occasionally comments in a speech bubble."

๐ŸŒŸ KAIROS โ€” Always-On Proactive Assistant

Feature Flag: KAIROS KAIROS biแบฟn Claude Code thร nh mแป™t always-on assistant cรณ khแบฃ nฤƒng:

  • Proactive mode โ€” Agent tแปฑ ฤ‘แป™ng chแบกy, tรฌm viแป‡c ฤ‘แปƒ lร m
  • SleepTool โ€” Sleep giแปฏa cรกc ticks (proactive polling)
  • PushNotificationTool โ€” Gแปญi push notifications cho user
  • SendUserFileTool โ€” Gแปญi files cho user
  • SubscribePRTool โ€” Theo dรตi GitHub PR events via webhooks
  • BriefTool โ€” Tแบกo brief summaries
  • CronTools โ€” Scheduled task execution (CronCreate/Delete/List)
  • MonitorTool โ€” System monitoring
  • RemoteTriggerTool โ€” Remote agent triggers
๐Ÿ”ฅ KAIROS = OpenClaw's Heartbeat on steroids. Anthropic ฤ‘ang build chรญnh xรกc pattern mร  OpenClaw ฤ‘รฃ cรณ โ€” proactive agent vแป›i scheduled tasks, push notifications, vร  PR monitoring. Nhฦฐng KAIROS sophisticated hฦกn vแป›i tick system, sleep budgets, vร  session history.

๐Ÿง  autoDream โ€” Background Memory Consolidation

Feature Flag: via isAutoDreamEnabled() autoDream chแบกy background memory consolidation โ€” literally "dreaming"! Nรณ:

  1. Time gate: โ‰ฅ24h since last consolidation
  2. Session gate: โ‰ฅ5 new sessions since last consolidation
  3. Lock: Only one consolidation at a time
  4. Fork agent: Spawns a read-only forked agent that reviews transcripts
  5. Consolidate: Updates MEMORY.md index, merges new info, prunes stale memories
consolidationPrompt.ts โ€” The Dream prompt
// Phase 1 โ€” Orient: ls memory dir, read MEMORY.md
// Phase 2 โ€” Gather: search transcripts for new signal
// Phase 3 โ€” Consolidate: merge into topic files
// Phase 4 โ€” Prune and index: keep MEMORY.md under 200 lines

// Tool constraints: Read-only bash only!
// `ls`, `find`, `grep`, `cat`, `stat`, `wc`, `head`, `tail`
// Anything that writes will be denied.

// Key insight: "Converting relative dates to absolute dates 
// so they remain interpretable after time passes"

๐Ÿ—บ๏ธ ULTRAPLAN โ€” Remote Opus Planning

Feature Flag: ULTRAPLAN User types "ultraplan" as keyword in prompt โ†’ launches remote Opus planning session via CCR (Claude Code Remote). Keyword detection with smart exclusion of quoted strings, paths, questions.

๐Ÿ•ต๏ธ Undercover Mode โ€” Anti-Leak System

Security ant-only Ironic that this got leaked! Undercover mode prevents Claude Code from leaking Anthropic-internal info when contributing to public repos:

  • Strips model codenames (Capybara, Tengu, etc.) from commits/PRs
  • Removes Co-Authored-By lines and AI attribution
  • "Write commit messages as a human developer would"
  • Auto-activates for all non-internal repos (safe default)
  • No force-OFF option โ€” guards against accidental leaks

๐ŸŽค Voice Mode

Feature Flag: VOICE_MODE Voice interaction via voice_stream endpoint on claude.ai. Requires Anthropic OAuth. Kill-switch via GrowthBook flag tengu_amber_quartz_disabled.

๐ŸŒ‰ Bridge Mode

Feature Flag: BRIDGE_MODE Remote control via daemon process. Enables IDE integrations, desktop apps, and remote sessions to control Claude Code.

๐Ÿ” Other Hidden Features

โœ‚๏ธ History Snip (HISTORY_SNIP)

Intelligent context window management โ€” snip old history to keep context fresh.

๐Ÿ“ฎ UDS Inbox (UDS_INBOX)

Unix Domain Socket peer discovery โ€” agent-to-agent communication on same machine.

๐Ÿ“œ Workflow Scripts (WORKFLOW_SCRIPTS)

Bundled workflow execution system with initBundledWorkflows().

๐Ÿ”ฅ Torch (TORCH)

Unknown feature โ€” command registered but code gated behind feature flag.

๐ŸชŸ Context Collapse (CONTEXT_COLLAPSE)

Advanced context management with CtxInspectTool for debugging.

๐Ÿ–ฅ๏ธ Terminal Panel (TERMINAL_PANEL)

TerminalCaptureTool for capturing terminal state.

๐Ÿ“

System Prompts & Prompt Engineering

Prompt Architecture โ–ผ

System Prompt Architecture

System prompt ฤ‘ฦฐแปฃc built dynamically tแปซ nhiแปu sections. Cรณ boundary marker chia static (cacheable globally) vร  dynamic (per-session) content:

prompts.ts โ€” System prompt structure
// STATIC sections (cached globally across users):
getSimpleIntroSection()      // Identity + cyber risk instruction
getSimpleSystemSection()     // System rules, tool results, hooks
getSimpleDoingTasksSection() // Coding guidelines, security
getActionsSection()          // Careful action execution
getUsingYourToolsSection()   // Tool usage patterns
getSimpleToneAndStyleSection() // Communication style
getOutputEfficiencySection()  // Output efficiency rules

// === BOUNDARY MARKER ===
SYSTEM_PROMPT_DYNAMIC_BOUNDARY  // Cache break point

// DYNAMIC sections (per-session, per-user):
session_guidance  // Agent tool section, skill guidance
memory            // Memory files (MEMORY.md, auto-memory)
env_info          // OS, CWD, shell, model info
language          // Language preference
output_style      // Custom output style
mcp_instructions  // MCP server instructions
scratchpad        // Scratchpad directory path
frc               // Function result clearing
token_budget      // Token budget instructions

Identity Prompt

system.ts โ€” Identity
const DEFAULT_PREFIX = 
  `You are Claude Code, Anthropic's official CLI for Claude.`

// SDK mode:
const AGENT_SDK_PREFIX = 
  `You are a Claude agent, built on Anthropic's Claude Agent SDK.`

// Frontier model reference:
const FRONTIER_MODEL_NAME = 'Claude Opus 4.6'

Cyber Risk Instruction (Security-critical)

cyberRiskInstruction.ts โ€” Owned by Safeguards team
// DO NOT MODIFY WITHOUT SAFEGUARDS TEAM REVIEW
// Owners: David Forsythe, Kyla Guru

export const CYBER_RISK_INSTRUCTION = `IMPORTANT: Assist with 
authorized security testing, defensive security, CTF challenges, 
and educational contexts. Refuse requests for destructive 
techniques, DoS attacks, mass targeting, supply chain compromise, 
or detection evasion for malicious purposes. Dual-use security 
tools (C2 frameworks, credential testing, exploit development) 
require clear authorization context.`

Key Prompt Engineering Patterns

1. "Don't Over-Engineer" Instructions

Claude Code has extensive anti-sloppy-code instructions:

prompts.ts โ€” Code style guidance
- Don't add features, refactor code, or make "improvements" beyond 
  what was asked. A bug fix doesn't need surrounding code cleaned up.
- Don't add error handling for scenarios that can't happen.
- Don't create helpers or abstractions for one-time operations.
- Three similar lines of code is better than a premature abstraction.
- Default to writing no comments. Only add when the WHY is non-obvious.
- Don't remove existing comments unless you're removing the code.

2. False-Claims Mitigation

prompts.ts โ€” Anti-hallucination (ant-only, for Capybara v8)
Report outcomes faithfully: if tests fail, say so with the relevant 
output; if you did not run a verification step, say that rather than 
implying it succeeded. Never claim "all tests pass" when output shows 
failures, never suppress or simplify failing checks to manufacture a 
green result, and never characterize incomplete work as done.

3. Numeric Length Anchors

prompts.ts โ€” Quantitative output control (ant-only)
// Research shows ~1.2% output token reduction vs qualitative "be concise"
'Length limits: keep text between tool calls to โ‰ค25 words. 
 Keep final responses to โ‰ค100 words unless the task requires more.'
๐Ÿ’ก Insight: Numeric length anchors (โ‰ค25 words, โ‰ค100 words) work 1.2% better than qualitative instructions ("be concise"). This is actionable for OpenClaw's system prompts.

4. Prompt Cache Optimization

Anthropic optimizes prompt caching obsessively:

  • Static vs dynamic boundary marker prevents cache busting
  • MCP instructions moved to delta attachments to avoid cache invalidation
  • Agent list moved to attachments (saved 10.2% of fleet cache_creation tokens!)
  • Tool sorting ensures cache stability
  • systemPromptSection() registry allows lazy evaluation and caching
๐Ÿง 

Memory & Persistence System

4 memory types ยท autoDream โ–ผ

Memory Architecture

Claude Code has a sophisticated multi-layer memory system:

graph TB A[CLAUDE.md Files] --> |Project rules| SP[System Prompt] B[Memory Directory] --> |MEMORY.md index| SP C[Auto-Extract] --> |Background agent| B D[autoDream] --> |Consolidation| B E[Team Memory] --> |Shared across users| SP subgraph "Memory Types" U[๐Ÿ‘ค User - role, prefs] F[๐Ÿ“ Feedback - corrections] P[๐Ÿ“‹ Project - ongoing work] R[๐Ÿ”— Reference - external links] end B --> U B --> F B --> P B --> R style A fill:#1a1e24,stroke:#58a6ff,color:#e6edf3 style B fill:#1a1e24,stroke:#3fb950,color:#e6edf3 style D fill:#1a1e24,stroke:#d29922,color:#e6edf3 style E fill:#1a1e24,stroke:#bc8cff,color:#e6edf3

4 Memory Types (Taxonomy)

TypeScopeWhatWhen to Save
userAlways privateUser's role, goals, knowledge, preferencesLearn user details
feedbackDefault privateCorrections AND confirmations from userUser corrects or validates approach
projectBias teamOngoing work, goals, deadlines, bugsLearn who does what, why, when
referenceUsually teamPointers to external systemsLearn about external resources

Memory File Format

Memory file with frontmatter
---
type: feedback
title: Integration tests must use real DB
created: 2026-03-05
---
Integration tests must hit a real database, not mocks.

**Why:** Prior incident where mock/prod divergence masked a broken migration.
**How to apply:** When writing tests for database-touching code, always use 
test database, never mocks.

What NOT to Save

Claude Code explicitly excludes:

  • Code patterns, architecture, file paths (derivable from code)
  • Git history (use git log)
  • Debugging solutions (fix is in the code)
  • Anything in CLAUDE.md files
  • Ephemeral task details
  • Even when user explicitly asks โ€” redirect to "what was surprising?"

Background Memory Extraction

After each conversation turn, a background agent extracts memories. It runs as a "perfect fork" of the main conversation โ€” same system prompt, same context. Only fires when the main agent didn't already write memories.

๐Ÿ’ก So sรกnh vแป›i OpenClaw: OpenClaw's Infinity Neural memory system uses similar concepts (auto-remember, memory types) but with a neural graph approach. Claude Code's file-based system is simpler but the 4-type taxonomy with scope guidance is more structured. The "feedback from success AND failure" pattern is particularly insightful.
๐Ÿ”’

Security & Safety Systems

Defense in Depth โ–ผ

Permission Modes

  • Normal mode โ€” Prompts user for each tool execution
  • Auto-accept (YOLO) mode โ€” Auto-classifier decides safety
  • bypassPermissions โ€” Skip all checks (dangerous, blocked on root)

BashTool Security (103KB!)

bashSecurity.ts alone is 103KB โ€” more security code than most entire projects:

  • Command parsing โ€” Full bash command parser (132KB bashParser.ts)
  • Path validation โ€” 44KB of path security checks
  • Sed validation โ€” 22KB of sed command analysis
  • Read-only validation โ€” 69KB for enforcing read-only mode
  • Destructive command detection โ€” Warns before rm, git reset, etc.
  • Sandbox mode โ€” filesystem read/write allowlists, network restrictions

cch Attestation โ€” Custom Bun Runtime

Security A fascinating anti-piracy/verification mechanism:

system.ts โ€” cch attestation
// cch=00000 placeholder in HTTP header
// Bun's NATIVE HTTP stack (Zig implementation) finds this placeholder
// in the serialized request body and OVERWRITES the zeros with a 
// computed hash AFTER JavaScript has finished.
// Server verifies this token to confirm request came from real 
// Claude Code client.

// Implementation: bun-anthropic/src/http/Attestation.zig
const cch = feature('NATIVE_CLIENT_ATTESTATION') 
  ? ' cch=00000;'  // same-length replacement avoids Content-Length changes
  : ''
๐Ÿ” Zig-level attestation: The cch token is computed in Zig (compiled into Bun binary), making it extremely difficult to reverse-engineer or fake. This is a hardware-level client verification โ€” the JavaScript layer only sees a placeholder. Brilliant security engineering.

Undercover Mode (Detailed)

undercover.ts โ€” Anti-leak instructions
## UNDERCOVER MODE โ€” CRITICAL

NEVER include in commit messages or PR descriptions:
- Internal model codenames (Capybara, Tengu, etc.)
- Unreleased model versions (opus-4-7, sonnet-4-8)
- Internal repo/project names
- Internal Slack channels or short links
- "Claude Code" or any mention that you are an AI
- Co-Authored-By lines

GOOD: "Fix race condition in file watcher initialization"
BAD:  "Fix bug found while testing with Claude Capybara"
BAD:  "1-shotted by claude-opus-4-6"

Safety in Actions Prompt

The system prompt has detailed guidance on reversibility and blast radius:

  • Freely allowed: editing files, running tests (local, reversible)
  • Requires confirmation: git push, creating PRs, sending messages, force operations
  • "Measure twice, cut once" โ€” investigate before deleting
  • Lock files: investigate what holds it, don't just delete
  • Merge conflicts: resolve, don't discard changes
  • User approving once โ‰  blanket approval
โ˜๏ธ

Services & Infrastructure

130 files ยท 49K lines โ–ผ

API Layer (claude.ts โ€” 126KB)

The API service handles all communication with Anthropic's API. Key features:

  • Streaming โ€” Full streaming support with tool use progress
  • Prompt caching โ€” Global scope + per-session scope with cache-break detection
  • Retry logic โ€” 28KB withRetry.ts with sophisticated error handling
  • Rate limit handling โ€” Claude.ai subscription limits, quota status extraction
  • Model selection โ€” Opus/Sonnet/Haiku with fast mode switching
  • Task budgets โ€” API-level task_budget for agentic turns
  • Effort levels โ€” Configurable effort (low/medium/high) per request

MCP Integration (119KB client)

Model Context Protocol client is a major component:

  • client.ts (119KB) โ€” Full MCP client implementation
  • auth.ts (89KB) โ€” OAuth flow for MCP servers
  • config.ts (52KB) โ€” MCP server configuration management
  • Support for stdio, SSE, and in-process transports
  • Elicitation handler for interactive MCP server UIs
  • Channel notifications and permissions

Analytics & Telemetry

  • GrowthBook (41KB) โ€” Feature flags + A/B testing (cached to disk)
  • Datadog โ€” Metrics export
  • First-party event logging โ€” Custom event pipeline
  • logEvent() โ€” Standardized event tracking throughout codebase
  • Events use tengu_ prefix (internal codename)

Cost Tracking

Full cost tracking with per-model breakdowns:

  • Input/output token counting
  • Cache read/creation token tracking
  • USD cost calculation per model
  • Session-level cost persistence
  • Lines added/removed tracking
  • API duration tracking (with and without retries)

Compact / Context Management

  • Auto-compact โ€” Automatic conversation compaction when approaching context limits
  • Reactive compact โ€” Feature-gated advanced compaction
  • Context collapse โ€” Collapse tool results into summaries
  • History snip โ€” Prune old history intelligently
  • Microcompact โ€” Fine-grained compaction boundaries

Model Codenames Decoded

CodenameContext
TenguClaude Code project codename (all events use tengu_ prefix)
CapybaraModel version codename (Capybara v8 = latest at leak time)
NumbatNext model version (referenced in output efficiency section comments)
Amber QuartzVoice mode (kill-switch flag name)
Onyx PloverautoDream feature (GrowthBook config name)
๐Ÿ–ฅ๏ธ

UI/UX Patterns โ€” React + Ink Terminal

REPL.tsx = 879KB โ–ผ

React Ink Architecture

The entire terminal UI is built with React components rendered via Ink. This is unconventional but powerful โ€” React's component model, hooks, and state management work naturally for complex TUIs.

Key UI Components

ComponentSizePurpose
REPL.tsx879KBMain screen โ€” messages, input, tools, everything
PromptInput.tsx349KBInput handling โ€” typeahead, vim mode, syntax highlight
ink.tsx248KBCustom Ink renderer extensions
Messages.tsx145KBMessage rendering with virtual scrolling
VirtualMessageList.tsx146KBVirtualized list for performance
Stats.tsx150KBStatistics and metrics panel
ScrollKeybindingHandler.tsx147KBKeyboard navigation

Vim Mode (1,358 lines)

Full Vim mode implementation with:

  • Motions โ€” h, j, k, l, w, b, e, $, ^, 0, gg, G, f/t + char
  • Operators โ€” d, c, y (delete, change, yank) with motion composition
  • Text Objects โ€” iw, aw, i", a", i(, a(, etc.
  • Transitions โ€” Normal โ†’ Insert โ†’ Visual mode state machine
  • Types โ€” Full TypeScript types for cursor, mode, registers

Theme System

Customizable color themes with named semantic colors (not raw hex). The /theme command renders a color picker UI.

๐Ÿ“š

Plugin & Skills System

4 skill sources โ–ผ

Skills Architecture

Skills are markdown files with frontmatter that get injected as prompts. 4 loading sources:

  1. Skill directories โ€” .claude/skills/ per project + ~/.claude/skills/ user-global
  2. Plugin skills โ€” From npm-style plugins with manifest
  3. Bundled skills โ€” Ship with the CLI binary
  4. Built-in plugin skills โ€” From enabled built-in plugins

Skill Frontmatter Format

Example skill file (.claude/skills/commit.md)
---
name: commit
description: Create a git commit with staged changes
whenToUse: After code changes are ready to commit
tools: [Bash, FileRead]
disallowedTools: [Agent, TodoWrite]
model: sonnet  # optional model override
effort: high   # optional effort level
shell:         # optional shell commands in prompt
  - "git status --short"
  - "git diff --cached"
---

# Commit Skill

Review the staged changes and create a meaningful commit message...

Plugin System

Plugins are npm-style packages with manifest, hooks, skills, and MCP servers:

  • Built-in plugins โ€” Ship with CLI, enable/disable via /plugin UI
  • Marketplace plugins โ€” External plugins with name@marketplace IDs
  • Hot reload โ€” Plugin hooks hot-reload when settings change
  • Plugin-only policy โ€” Restrict certain tools to plugin-provided only

Experimental: Skill Search

Feature Flag: EXPERIMENTAL_SKILL_SEARCH DiscoverSkillsTool + local search index for finding relevant skills automatically during conversation.

๐Ÿ’ก OpenClaw comparison: OpenClaw's skill system (from ClawHub) is very similar in concept โ€” markdown files with frontmatter, loaded from directories. The key difference: Claude Code has DiscoverSkillsTool for automatic skill surfacing, while OpenClaw relies on <available_skills> in the system prompt. The automatic surfacing approach is more scalable.
๐Ÿ’ก

Lessons for OpenClaw โ€” What We Can Learn

Actionable Insights โ–ผ

โœ… Patterns Worth Adopting

1. buildTool() Factory Pattern

Single factory function with fail-closed defaults. Every tool goes through it. Prevents bugs from missing method implementations. OpenClaw should adopt this for tool registration.

2. Memory Type Taxonomy

4-type system (user, feedback, project, reference) with clear scope guidance. "Record from failure AND success" โ€” brilliant insight. Our Infinity Neural could benefit from this structured approach.

3. autoDream Consolidation

Background memory consolidation during idle periods. Time + session gates prevent over-consolidation. Read-only fork agent prevents corruption. We should implement similar in Infinity Neural.

4. Coordinator "Never Delegate Understanding"

The principle that coordinators must synthesize findings before delegating implementation. Prevents lazy delegation. Should be core to OpenClaw's multi-agent patterns.

5. Numeric Length Anchors

Using โ‰ค25 words / โ‰ค100 words instead of qualitative "be concise" โ€” 1.2% token reduction. Concrete, measurable, enforceable. Apply to OpenClaw's SOUL.md.

6. Prompt Cache Boundary

Static/dynamic boundary in system prompt lets static content cache globally across users. Agent list moved to attachments saved 10.2% cache tokens. Architecture-level optimization.

7. Deferred Tool Loading (ToolSearch)

Tools marked shouldDefer aren't loaded until ToolSearchTool finds them relevant. Reduces prompt size for 40+ tool systems.

8. Fork Subagents

Forking yourself (inheriting context + cache) vs spawning fresh agents. Cheap because shares prompt cache. "Don't peek" at fork output โ€” trust completion notification.

โŒ Things They Do Wrong / We Should Avoid

๐Ÿšซ Monolithic Bundles

main.tsx = 789KB, REPL.tsx = 879KB. These are unmaintainable monoliths. Even with React components, single files shouldn't exceed 100KB. OpenClaw's modular skill system is better.

๐Ÿšซ Over-Reliance on Feature Flags

30+ feature flags create combinatorial explosion of possible states. Testing all combinations is impossible. OpenClaw's simpler feature set is more maintainable.

๐Ÿšซ Complexity in Security

103KB for BashTool security alone suggests the permission model is too complex. Each new tool needs extensive security code. A simpler sandboxing approach (like containers) would be more robust.

๐Ÿšซ Vendor Lock-in (Bun Fork)

Custom Bun fork with Zig-compiled attestation creates massive vendor lock-in. Node.js compatibility is broken. OpenClaw's Node.js-based approach is more portable.

๐Ÿ”„ Things We Already Do Better

Claude Code

  • File-based memory (MEMORY.md + files)
  • Background extraction agent
  • Manual memory pruning via autoDream
  • 4-type taxonomy (rigid)

OpenClaw (Infinity Neural)

  • Neural graph memory with spreading activation
  • Real-time auto-remember with dedup
  • Hypothesis tracking + prediction verification
  • 10+ memory types + metacognition (gaps)

Claude Code Multi-Agent

  • Coordinator mode (separate system prompt)
  • Workers can't see coordinator conversation
  • XML task notifications
  • Fork subagent (shares cache)

OpenClaw Multi-Agent

  • sessions_spawn with flexible runtime (acp, exec)
  • Auto-announce completion (push-based)
  • Cross-session memory sharing via Neural Memory
  • Model-agnostic (any LLM provider)
๐Ÿ“Š

Code Quality Assessment

Professional Grade โ–ผ

Overall Assessment: โญโญโญโญ (4/5)

Strengths

  • TypeScript usage: Excellent โ€” strict types, sophisticated generics (BuiltTool<D>), branded types, proper Zod integration
  • Error handling: Very thorough โ€” try-catch everywhere, graceful degradation, error boundaries
  • Documentation: Extensive JSDoc comments with architectural context, not just "what" but "why"
  • Separation of concerns: Tool system is well-abstracted with clean interfaces
  • Security mindset: Defense-in-depth throughout โ€” fail-closed defaults, multiple validation layers
  • Performance awareness: Memoization, lazy loading, cache optimization, scan throttling

Weaknesses

  • File sizes: Multiple files >100KB โ€” REPL.tsx (879KB), PromptInput.tsx (349KB). These are maintenance nightmares
  • Monolithic architecture: Despite React components, too much logic in too few files
  • Feature flag complexity: 30+ flags create testing combinatorial explosion
  • Import complexity: Heavy use of conditional require() and lazy imports makes dependency graph hard to follow
  • Comments hint at tech debt: Multiple "@[MODEL LAUNCH]" TODOs, "un-gate once validated" notes

Notable Code Patterns

1. Memoized Config with Cache Clearing

Pattern: Memoize with explicit cache invalidation
export const getUserContext = memoize(async () => {
  const claudeMd = getClaudeMds(await getMemoryFiles())
  return { claudeMd, currentDate: `Today's date is ${getLocalISODate()}.` }
})
// Cache cleared explicitly when state changes:
getUserContext.cache.clear?.()

2. Feature-Gated Dead Code Elimination

Pattern: Build-time DCE via feature()
// bun:bundle feature() evaluates at BUILD TIME
// Entire code blocks are stripped from output when false
const buddy = feature('BUDDY')
  ? require('./commands/buddy/index.js').default
  : null  // DCE removes the require() entirely

3. Defensive Config Reading

Pattern: Per-field validation of cached config
// GrowthBook cache can return stale wrong-type values
function getConfig(): AutoDreamConfig {
  const raw = getFeatureValue_CACHED_MAY_BE_STALE('tengu_onyx_plover', null)
  return {
    minHours:
      typeof raw?.minHours === 'number' &&
      Number.isFinite(raw.minHours) &&
      raw.minHours > 0
        ? raw.minHours
        : DEFAULTS.minHours,
    // ... same for each field
  }
}

Testing Approach

Based on code patterns (test utilities, TestingPermissionTool, test environment checks), the project uses:

  • Unit tests with mock/stub patterns
  • Integration tests for tool execution
  • Eval-driven prompt testing (referenced in memory type comments)
  • Transcript search fidelity tests
  • Feature flag testing via environment variables

๐Ÿ”ฌ Claude Code Deep Dive Report โ€” Nacharium Research Lab

Generated 2026-03-31 | Source: npm sourcemap leak | Analysis by Mula Nacharis

477,418 lines of TypeScript analyzed across 1,884 files