CoderClaw Architecture
このコンテンツはまだ日本語訳がありません。
CoderClaw Architecture
Section titled “CoderClaw Architecture”This document describes the architectural design and implementation of CoderClaw, the multi-agent developer system.
System Overview
Section titled “System Overview”CoderClaw is designed as an orchestration engine that sits inside developer workflows, providing:
- Deep codebase understanding through AST parsing and semantic analysis
- Intelligent agent coordination for complex development tasks
- Persistent project context stored in
.coderClaw/directories - Extensible agent roles that can be customized per project
- Distributed execution with security boundaries
Architecture Layers
Section titled “Architecture Layers”Layer 1: Knowledge Engine
Section titled “Layer 1: Knowledge Engine”The foundation layer responsible for understanding code structure and context.
Knowledge Engine Components
Section titled “Knowledge Engine Components”AST Parser (src/coderclaw/ast-parser.ts)
- Parses TypeScript/JavaScript files using TypeScript Compiler API
- Extracts semantic information: functions, classes, interfaces, types
- Tracks visibility, parameters, return types, modifiers
- Exports metadata for downstream analysis
Code Map Builder (src/coderclaw/code-map.ts)
- Builds semantic code maps across entire projects
- Tracks import/export relationships
- Creates dependency graphs
- Calculates impact radius for changes
- Identifies coupling and module boundaries
Git History Tool (src/coderclaw/tools/git-history-tool.ts)
- Analyzes commit history via native git commands
- Tracks file evolution and authorship
- Identifies change patterns and hotspots
- Provides data for refactoring decisions
Project Context (src/coderclaw/project-context.ts)
- Manages
.coderClaw/directory structure - Loads/saves project metadata, rules, architecture
- Handles custom agent role definitions
- Provides persistence layer for project knowledge
Data Flow
Section titled “Data Flow”Source Files → AST Parser → File Metadata ↓ Code Map Builder → Dependency Graph ↓ Git History → Change Patterns ↓ Project Context → Persistent Storage (.coderClaw/)Layer 2: Agent System
Section titled “Layer 2: Agent System”The middle layer responsible for agent role definitions and capabilities.
Agent System Components
Section titled “Agent System Components”Agent Roles (src/coderclaw/agent-roles.ts)
- Defines 7 built-in agent roles
- Specifies capabilities, tools, system prompts
- Provides role lookup and discovery
- Supports custom role extensions
Built-in Roles:
- Code Creator: Feature implementation
- Code Reviewer: Quality and security review
- Test Generator: Comprehensive test creation
- Bug Analyzer: Systematic debugging
- Refactor Agent: Structure improvement
- Documentation Agent: Clear documentation
- Architecture Advisor: Design guidance
Custom Agent Loading
- Loads YAML definitions from
.coderClaw/agents/ - Merges with built-in roles
- Supports project-specific agent definitions
- Enables community-driven agent libraries
Agent Lifecycle
Section titled “Agent Lifecycle”Agent Request → Role Selection → Capability Check ↓ Tool Access Grant ↓ Execution Context ↓ Result CollectionLayer 3: Orchestration Engine
Section titled “Layer 3: Orchestration Engine”The top layer responsible for coordinating multiple agents.
Orchestration Engine Components
Section titled “Orchestration Engine Components”Enhanced Orchestrator (src/coderclaw/orchestrator-enhanced.ts)
- Creates and manages workflows
- Coordinates multi-agent execution
- Tracks task dependencies
- Aggregates results
- Integrates with distributed task engine
Task Engine (src/transport/task-engine.ts)
- Manages distributed task lifecycle
- State machine: PENDING → PLANNING → RUNNING → COMPLETED
- Event logging and audit trails
- Resumable execution support
- Progress tracking
Workflow Patterns
- Pre-defined patterns: feature, bugfix, refactor
- Custom workflow support
- Dependency resolution
- Parallel execution where possible
Orchestration Flow
Section titled “Orchestration Flow”Workflow Request → Step Definition → Dependency Analysis ↓ Task Scheduling ↓ Agent Spawning ↓ Execution Monitoring ↓ Result AggregationLayer 4: Integration Layer
Section titled “Layer 4: Integration Layer”The outer layer connecting to CoderClaw infrastructure.
Integration Layer Components
Section titled “Integration Layer Components”Tool System Integration
- Uses CoderClaw’s
AgentToolinterface - Registers coderClaw tools:
code_analysis,project_knowledge,git_history,orchestrate,workflow_status - Follows CoderClaw tool conventions
Subagent Integration
- Leverages CoderClaw’s subagent spawning
- Integrates with session management
- Respects tool policy and security boundaries
Transport Layer
- Local execution via
LocalTransportAdapter - Remote execution support (future)
- Protocol-agnostic runtime interface
Security Service
- RBAC enforcement
- Device trust verification
- Session-level permissions
- Audit logging
Integration Points
Section titled “Integration Points”CoderClaw Tools ←→ CoderClaw Tool SystemOrchestrator ←→ CoderClaw Subagent SpawningTask Engine ←→ Transport LayerSecurity ←→ CoderClaw Security ServiceData Structures
Section titled “Data Structures”Project Context (.coderClaw/context.yaml)
Section titled “Project Context (.coderClaw/context.yaml)”version: 1projectName: my-projectdescription: Project descriptionrootPath: /path/to/projectlanguages: - typescript - javascriptframeworks: - express - reactarchitecture: style: layered layers: - presentation - business - data patterns: - mvc - repositorybuildSystem: npmtestFramework: vitestlintingTools: - eslint - prettierdependencies: production: express: ^4.18.0 development: vitest: ^1.0.0customRules: - No direct database access from controllersmetadata: createdAt: 2026-02-19Project Rules (.coderClaw/rules.yaml)
Section titled “Project Rules (.coderClaw/rules.yaml)”version: 1codeStyle: indentation: spaces indentSize: 2 lineLength: 100 namingConventions: classes: PascalCase functions: camelCasetesting: required: true coverage: 80 frameworks: - vitestdocumentation: required: true format: markdown location: docs/git: branchNaming: "feature/*, fix/*, docs/*" commitFormat: conventional requireReview: trueconstraints: - Must pass all tests before commit - Must maintain 80% code coveragecustomRules: - Use async/await instead of promisesCustom Agent Role (.coderClaw/agents/custom.yaml)
Section titled “Custom Agent Role (.coderClaw/agents/custom.yaml)”name: custom-agentdescription: Project-specific agentcapabilities: - Capability 1 - Capability 2tools: - create - edit - viewsystemPrompt: | You are a custom agent. Follow project-specific guidelines.model: anthropic/claude-sonnet-4-20250514thinking: mediumconstraints: - Must follow constraint 1Code Map Structure
Section titled “Code Map Structure”type CodeMap = { files: Map<string, FileInfo>; dependencies: Map<string, string[]>; exports: Map<string, ExportInfo>; imports: Map<string, ImportInfo[]>;};
type FileInfo = { path: string; language: string; size: number; lastModified: Date; functions: FunctionInfo[]; classes: ClassInfo[]; interfaces: InterfaceInfo[]; types: TypeInfo[];};
type DependencyNode = { file: string; dependencies: string[]; dependents: string[];};Task State
Section titled “Task State”type TaskState = { id: string; // UUID description: string; agentId?: string; status: TaskStatus; // pending, planning, running, completed, failed, cancelled input?: string; output?: string; error?: string; createdAt: Date; startedAt?: Date; completedAt?: Date; progress?: number; // 0-100 metadata?: Record<string, unknown>;};Execution Flow
Section titled “Execution Flow”Project Initialization
Section titled “Project Initialization”1. User runs `coderclaw init`2. CLI prompts for project information3. Create .coderClaw/ directory structure4. Generate default context.yaml5. Generate default architecture.md6. Generate default rules.yaml7. Create agents/, skills/, memory/ subdirectories8. Write README.md explaining structureCode Analysis Request
Section titled “Code Analysis Request”1. Agent receives code analysis request2. Load project context from .coderClaw/3. Parse relevant source files with AST parser4. Build code map with dependencies5. Generate dependency graph6. Calculate metrics (coupling, complexity)7. Format and return structured resultsMulti-Agent Workflow
Section titled “Multi-Agent Workflow”1. User requests feature development2. Orchestrator loads workflow pattern3. Identify required agents (Architecture Advisor, Code Creator, Test Generator, Reviewer)4. Create workflow with task dependencies5. Spawn Architecture Advisor → analyze design6. Spawn Code Creator → implement feature (depends on analysis)7. Spawn Test Generator → create tests (depends on implementation)8. Spawn Code Reviewer → review code (depends on implementation)9. Aggregate results from all agents10. Present combined output to userGit-Aware Refactoring
Section titled “Git-Aware Refactoring”1. Load git history for target files2. Identify change patterns and hotspots3. Calculate file coupling metrics4. Spawn Refactor Agent with context5. Agent proposes refactoring strategy6. Validate with Test Generator7. Execute refactoring8. Verify tests still passTechnology Choices
Section titled “Technology Choices”Why TypeScript?
Section titled “Why TypeScript?”- Strong typing for tool interfaces
- Excellent AST support via TypeScript Compiler API
- Familiar to most developers
- Good performance for orchestration tasks
Why YAML for Configuration?
Section titled “Why YAML for Configuration?”- Human-readable and editable
- Standard format for project config
- Good tool support
- Easy to version control
Why Markdown for Documentation?
Section titled “Why Markdown for Documentation?”- Universal format
- Git-friendly
- Renders well in all viewers
- Easy to edit
Why SQLite for Memory?
Section titled “Why SQLite for Memory?”- Embedded database, no server needed
- ACID transactions
- Good query performance
- Portable files
Security Considerations
Section titled “Security Considerations”Sandboxing
Section titled “Sandboxing”- Code analysis runs with same permissions as other tools
- No arbitrary code execution during analysis
- Project context files are read-only during execution
RBAC Integration
Section titled “RBAC Integration”- Workflow execution respects CoderClaw’s tool policy
- Agent spawning follows security boundaries
- Distributed execution requires authentication
Data Privacy
Section titled “Data Privacy”- Project context stays local by default
- No external network access during analysis
- Git history analyzed locally
- Optional remote orchestration with encryption
Performance Optimization
Section titled “Performance Optimization”Caching
Section titled “Caching”- Parsed AST results cached in memory
- Code maps incrementally updated
- Git history cached with invalidation
Incremental Analysis
Section titled “Incremental Analysis”- Only re-parse changed files
- Update dependency graph incrementally
- Track file modification times
Parallel Execution
Section titled “Parallel Execution”- Independent agents run in parallel
- AST parsing parallelized per file
- Workflow tasks respect dependencies
Extensibility Points
Section titled “Extensibility Points”1. Language Support
Section titled “1. Language Support”Add new AST parsers in src/coderclaw/:
export async function parsePythonFile(filePath: string): Promise<FileInfo>;2. Custom Agents
Section titled “2. Custom Agents”Define YAML in .coderClaw/agents/:
name: my-agentcapabilities: [...]3. Custom Tools
Section titled “3. Custom Tools”Add to .coderClaw/skills/:
export const myTool: AgentTool = { name: "my_tool", execute: async () => { ... }};4. Transport Adapters
Section titled “4. Transport Adapters”Implement RuntimeInterface:
class HTTPTransportAdapter implements RuntimeInterface { async submitTask(request: TaskSubmitRequest): Promise<TaskState> { ... }}5. Workflow Patterns
Section titled “5. Workflow Patterns”Define in orchestrator:
const customWorkflow: WorkflowPattern = { name: "custom", steps: [...]};Testing Strategy
Section titled “Testing Strategy”Unit Tests
Section titled “Unit Tests”- AST parser: Parse sample files, verify structure
- Code map: Build graphs, verify dependencies
- Agent roles: Validate role definitions
- Orchestrator: Test workflow creation and execution
Integration Tests
Section titled “Integration Tests”- Full workflow execution end-to-end
- Project initialization and loading
- Multi-agent coordination
- Tool integration
E2E Tests
Section titled “E2E Tests”- Real project analysis
- Git history integration
- Custom agent loading
- Workflow execution with real agents
Future Architecture
Section titled “Future Architecture”Planned Enhancements
Section titled “Planned Enhancements”Multi-Language Support
- Python AST parser (ast module)
- Go parser (go/ast package)
- Java parser (JavaParser library)
- Rust parser (syn crate)
Real-Time Indexing
- File system watcher integration
- Incremental re-parsing
- Live dependency updates
IDE Integration
- Language Server Protocol support
- Live error detection
- Real-time suggestions
Distributed Execution
- HTTP transport adapter
- WebSocket for streaming
- gRPC for performance
- Load balancing across nodes
Enhanced Semantic Search
- Natural language queries
- Vector embeddings for code
- Similarity search
- Cross-repository search
Conclusion
Section titled “Conclusion”CoderClaw’s architecture is designed to be:
- Modular: Clear separation of concerns across layers
- Extensible: Multiple extension points for customization
- Performant: Caching and parallelization strategies
- Secure: Integrated security model with RBAC and device trust
- Developer-Friendly: Clear APIs and documentation
The layered design ensures that each component can evolve independently while maintaining a cohesive system.