claude-code-source-analysis
```markdown
What this skill does
```markdown
---
name: claude-code-source-analysis
description: Expertise in exploring, understanding, and extending the Claude Code decompiled source archive and its Python reimplementation (claw-code)
triggers:
- explore claude code source code
- understand claude code architecture
- analyze claude code internals
- work with claude code tools system
- study claude code agent loop
- implement claude code patterns
- extend claude code slash commands
- understand claude code memory system
---
# Claude Code Source Code Collection
> Skill by [ara.so](https://ara.so) — Daily 2026 Skills collection
A research repository containing the decompiled TypeScript source of Claude Code v2.1.88 (~163,318 lines across 1,884 files) and a clean-room Python reimplementation (`claw-code`). Use this repository to study, extend, or reimplement Anthropic's CLI coding agent.
---
## Repository Structure
```
collection-claude-code-source-code/
├── claude-code-source-code/ # Decompiled TypeScript (v2.1.88)
│ └── src/
│ ├── main.tsx # CLI entry + REPL bootstrap
│ ├── query.ts # Core agent loop (785KB)
│ ├── QueryEngine.ts # SDK/Headless lifecycle engine
│ ├── Tool.ts # Tool interface + buildTool factory
│ ├── commands.ts # Slash command definitions
│ ├── tools/ # 40+ tool implementations
│ ├── commands/ # ~87 slash command handlers
│ ├── components/ # React/Ink terminal UI
│ ├── services/ # Business logic layer
│ ├── coordinator/ # Multi-agent coordination
│ ├── memdir/ # Long-term memory management
│ └── plugins/ # Plugin system
├── claw-code/ # Python clean-room rewrite (66 files)
└── docs/ # Bilingual analysis (en/ + zh/)
```
---
## Installation & Setup
```bash
# Clone the repository
git clone https://github.com/chauncygu/collection-claude-code-source-code.git
cd collection-claude-code-source-code
# Explore the TypeScript source
cd claude-code-source-code
npm install # if package.json dependencies are needed for tooling
# Work with the Python rewrite
cd ../claw-code
pip install -r requirements.txt
```
---
## Core Architecture: The Agent Loop
The central execution model lives in `src/query.ts`. Understanding it is key to understanding the whole system.
```typescript
// Simplified agent loop pattern from query.ts
async function* query(
userMessage: string,
context: ConversationContext,
tools: Tool[],
): AsyncGenerator<SDKMessage> {
// 1. Assemble system prompt from parts
const systemPromptParts = await fetchSystemPromptParts(context);
// 2. Run streaming tool executor with auto-compaction
const executor = new StreamingToolExecutor(tools);
while (true) {
const response = await callClaude({ systemPromptParts, userMessage, tools });
// 3. Yield streamed messages back to consumer
for await (const chunk of response) {
yield chunk;
}
// 4. Execute tool calls in parallel
const toolResults = await executor.runTools(response.toolCalls);
// 5. Auto-compact context if approaching token limit
if (shouldCompact(context)) {
await autoCompact(context);
}
if (!hasMoreToolCalls(response)) break;
}
}
```
### Entry Point Pattern (`main.tsx`)
```typescript
// CLI bootstrap pattern
import { render } from 'ink';
import { App } from './components/App';
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.headless) {
// SDK/headless mode via QueryEngine
const engine = new QueryEngine(args);
await engine.run();
} else {
// Interactive REPL mode via React/Ink
render(<App initialArgs={args} />);
}
}
main().catch(console.error);
```
---
## Tool System
### Tool Interface (`src/Tool.ts`)
```typescript
interface Tool {
name: string;
description: string;
inputSchema: ZodSchema;
execute(input: unknown, context: ToolContext): Promise<ToolResult>;
}
// buildTool factory pattern
const MyTool = buildTool({
name: 'my_tool',
description: 'Does something useful',
inputSchema: z.object({
path: z.string().describe('File path to operate on'),
content: z.string().optional(),
}),
async execute({ path, content }, ctx) {
// tool implementation
return { type: 'text', text: `Processed ${path}` };
},
});
```
### Key Built-in Tools
```typescript
// File operations
import { FileReadTool } from './tools/FileReadTool';
import { FileEditTool } from './tools/FileEditTool';
import { FileWriteTool } from './tools/FileWriteTool';
// Code search
import { GlobTool } from './tools/GlobTool';
import { GrepTool } from './tools/GrepTool';
// Execution
import { BashTool } from './tools/BashTool';
// Web
import { WebFetchTool } from './tools/WebFetchTool';
import { WebSearchTool } from './tools/WebSearchTool';
// Sub-agents
import { AgentTool } from './tools/AgentTool';
// Memory
import { TodoWriteTool } from './tools/TodoWriteTool';
```
### Registering Tools (`src/tools.ts`)
```typescript
// Tool registration pattern
export function getTools(config: Config): Tool[] {
const baseTools = [
FileReadTool,
FileEditTool,
FileWriteTool,
GlobTool,
GrepTool,
BashTool,
];
if (config.enableWebTools) {
baseTools.push(WebFetchTool, WebSearchTool);
}
if (config.enableAgentTools) {
baseTools.push(AgentTool);
}
return baseTools;
}
```
---
## Slash Commands
### Command Definition Pattern (`src/commands/`)
```typescript
// Pattern for defining a slash command
export const reviewCommand = {
name: 'review',
description: 'Review code changes',
aliases: ['/review'],
async execute(args: string[], context: CommandContext) {
const diff = await context.tools.bash.execute('git diff HEAD');
return context.query(`Please review these changes:\n${diff}`);
},
};
// Registration in commands.ts
export const SLASH_COMMANDS = [
reviewCommand,
commitCommand,
sessionCommand,
memoryCommand,
configCommand,
// ... ~87 total
];
```
### Common Slash Commands Reference
| Command | Purpose |
|---|---|
| `/commit` | Stage and commit changes |
| `/commit-push-pr` | Commit, push, and open PR |
| `/review` | Review current diff |
| `/resume` | Resume last session |
| `/memory` | Manage long-term memory |
| `/config` | Edit configuration |
| `/skills` | List available skills |
| `/permissions` | Manage tool permissions |
| `/mcp` | MCP server management |
| `/vim` | Toggle vim keybindings |
---
## Permission System
```typescript
// Three permission modes
type PermissionMode = 'default' | 'bypass' | 'strict';
// default → ask user before executing sensitive tools
// bypass → auto-allow all tools (headless/CI use)
// strict → auto-deny all unwhitelisted tools
// Permission rule structure
interface PermissionRule {
tool: string; // e.g. 'bash', 'file_write'
pattern?: string; // glob pattern for path-based rules
mode: PermissionMode;
}
// Checking permissions at runtime
async function checkPermission(
tool: Tool,
input: unknown,
rules: PermissionRule[],
): Promise<'allow' | 'deny' | 'ask'> {
const matchingRule = rules.find(r => matchesRule(r, tool, input));
if (matchingRule) return matchingRule.mode === 'bypass' ? 'allow' : 'deny';
return 'ask'; // default: prompt user
}
```
---
## Context Management & Auto-Compaction
```typescript
// Auto-compact strategies from query.ts
type CompactionStrategy =
| 'reactive' // compress when near token limit
| 'micro' // compress small incremental chunks
| 'trimmed'; // trim oldest turns first
async function autoCompact(
context: ConversationContext,
strategy: CompactionStrategy = 'reactive',
): Promise<void> {
const tokenCount = await estimateTokens(context.messages);
if (tokenCount > CONTEXT_COLLAPSE_THRESHOLD) {
const summary = await summarizeHistory(context.messRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.