Claw-Code 项目深度分析 架构设计分析

2.1 系统整体架构

高层次架构图

┌─────────────────────────────────────────────────────────────────┐
│                      Claw-Code 系统架构                          │
│                                                                 │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │                    用户接口层                             │  │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │  │
│   │  │   CLI       │  │   API       │  │   SDK       │     │  │
│   │  │  命令行界面  │  │  REST API   │  │  开发工具包  │     │  │
│   │  └─────────────┘  └─────────────┘  └─────────────┘     │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │                    核心引擎层                             │  │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │  │
│   │  │   Task      │  │  Commands   │  │   Tools     │     │  │
│   │  │  任务管理   │  │  命令系统   │  │  工具系统   │     │  │
│   │  └─────────────┘  └─────────────┘  └─────────────┘     │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │                    数据模型层                             │  │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │  │
│   │  │   Models    │  │   Query     │  │   Manifest  │     │  │
│   │  │  数据类     │  │  查询引擎   │  │  清单系统   │     │  │
│   │  └─────────────┘  └─────────────┘  └─────────────┘     │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │                    基础设施层                             │  │
│   │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │  │
│   │  │   File I/O  │  │   Network   │  │   Security  │     │  │
│   │  │  文件系统   │  │  网络通信   │  │  安全机制   │     │  │
│   │  └─────────────┘  └─────────────┘  └─────────────┘     │  │
│   └─────────────────────────────────────────────────────────┘  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

2.2 仓库结构

目录布局

claw-code/
├── src/                                # Python 移植工作区
│   ├── __init__.py                     # 包初始化
│   ├── main.py                         # CLI 入口点
│   ├── models.py                       # 数据模型定义
│   ├── commands.py                     # 命令端口元数据
│   ├── tools.py                        # 工具端口元数据
│   ├── task.py                         # 任务管理
│   ├── query_engine.py                 # 查询引擎
│   └── port_manifest.py                # 移植清单
│
├── tests/                              # Python 验证测试
│   ├── __init__.py
│   ├── test_models.py
│   ├── test_commands.py
│   ├── test_tools.py
│   └── test_integration.py
│
├── assets/                             # 资源文件
│   ├── clawd-hero.jpeg                 # 项目横幅
│   ├── tweet-screenshot.png            # 推文截图
│   ├── wsj-feature.png                 # WSJ 报道
│   └── omx/                            # OmX 工作流截图
│       ├── omx-readme-review-1.png
│       └── omx-readme-review-2.png
│
├── 2026-03-09-is-legal-the-same-as-legitimate-ai-reimplementation-and-the-erosion-of-copyleft.md
│
└── README.md                           # 项目说明

模块依赖关系

┌─────────────────────────────────────────────────────────────┐
│                    模块依赖图                                │
│                                                             │
│                      ┌───────────┐                          │
│                      │  main.py  │                          │
│                      │  (入口)   │                          │
│                      └─────┬─────┘                          │
│                            │                                │
│           ┌────────────────┼────────────────┐               │
│           │                │                │               │
│           ▼                ▼                ▼               │
│    ┌────────────┐  ┌────────────┐  ┌────────────┐          │
│    │ commands.py│  │  tools.py  │  │  task.py   │          │
│    │  (命令)    │  │  (工具)    │  │  (任务)    │          │
│    └─────┬──────┘  └─────┬──────┘  └─────┬──────┘          │
│          │               │               │                  │
│          └───────────────┼───────────────┘                  │
│                          ▼                                  │
│                   ┌─────────────┐                           │
│                   │  models.py  │                           │
│                   │  (数据模型)  │                           │
│                   └──────┬──────┘                           │
│                          │                                  │
│          ┌───────────────┼───────────────┐                  │
│          ▼               ▼               ▼                  │
│   ┌────────────┐ ┌────────────┐ ┌────────────┐             │
│   │   query    │ │   port     │ │  utils     │             │
│   │  _engine   │ │  manifest  │ │  (工具)    │             │
│   └────────────┘ └────────────┘ └────────────┘             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2.3 核心模块详解

2.3.1 main.py - CLI 入口点

职责: 命令行接口,提供项目信息查询和系统控制

主要命令:

# 使用示例
python3 -m src.main summary        # 渲染 Python 移植摘要
python3 -m src.main manifest       # 打印工作区清单
python3 -m src.main subsystems     # 列出 Python 模块
python3 -m src.main commands       # 检查命令清单
python3 -m src.main tools          # 检查工具清单
python3 -m src.main parity-audit   # 运行对等审计

代码结构:

#!/usr/bin/env python3
"""
Claw-Code CLI Entry Point

提供命令行接口用于:
- 查询移植状态
- 检查命令/工具清单
- 运行验证测试
- 执行对等审计
"""

import argparse
import sys
from .query_engine import render_summary
from .port_manifest import print_manifest
from .models import list_subsystems

def main():
    parser = argparse.ArgumentParser(description='Claw-Code CLI')
    subparsers = parser.add_subparsers(dest='command')
    
    # summary 命令
    summary_parser = subparsers.add_parser('summary', 
                                           help='Render porting summary')
    
    # manifest 命令
    manifest_parser = subparsers.add_parser('manifest',
                                            help='Print workspace manifest')
    
    # subsystems 命令
    subsystems_parser = subparsers.add_parser('subsystems',
                                              help='List Python modules')
    subsystems_parser.add_argument('--limit', type=int, default=16)
    
    # ... 其他命令
    
    args = parser.parse_args()
    
    if args.command == 'summary':
        render_summary()
    elif args.command == 'manifest':
        print_manifest()
    elif args.command == 'subsystems':
        list_subsystems(limit=args.limit)
    # ... 其他命令处理

if __name__ == '__main__':
    main()

2.3.2 models.py - 数据模型

职责: 定义系统数据结构,使用 Python dataclasses

核心数据类:

from dataclasses import dataclass, field
from typing import List, Dict, Optional
from enum import Enum

class SubsystemStatus(Enum):
    """子系统状态枚举"""
    NOT_STARTED = "not_started"
    IN_PROGRESS = "in_progress"
    COMPLETE = "complete"
    VERIFIED = "verified"

@dataclass
class Subsystem:
    """子系统定义"""
    name: str
    description: str
    status: SubsystemStatus
    modules: List[str] = field(default_factory=list)
    completed_modules: int = 0
    total_modules: int = 0
    
    @property
    def progress(self) -> float:
        """计算完成进度"""
        if self.total_modules == 0:
            return 0.0
        return self.completed_modules / self.total_modules

@dataclass
class Module:
    """模块定义"""
    name: str
    subsystem: str
    status: SubsystemStatus
    lines_of_code: int = 0
    test_coverage: float = 0.0
    dependencies: List[str] = field(default_factory=list)

@dataclass
class BacklogItem:
    """待办事项"""
    id: str
    title: str
    description: str
    priority: int  # 1-5, 5 最高
    status: str
    assignee: Optional[str] = None

模型关系图:

┌─────────────────────────────────────────────────────────────┐
│                    数据模型关系                              │
│                                                             │
│   ┌──────────────┐         ┌──────────────┐                │
│   │  Subsystem   │1      * │    Module    │                │
│   │  子系统      │─────────│    模块      │                │
│   └──────────────┘         └──────────────┘                │
│         │                        │                          │
│         │                        │                          │
│         ▼                        ▼                          │
│   ┌──────────────┐         ┌──────────────┐                │
│   │ BacklogItem  │         │    Command   │                │
│   │  待办事项    │         │    命令      │                │
│   └──────────────┘         └──────────────┘                │
│                                                             │
│   关系说明:                                                 │
│   - 1 个子系统包含多个模块                                    │
│   - 模块有状态和依赖关系                                      │
│   - 待办事项追踪开发进度                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2.3.3 commands.py - 命令系统

职责: 定义和管理系统命令端口

命令元数据:

@dataclass
class CommandPort:
    """命令端口定义"""
    name: str
    description: str
    parameters: Dict[str, ParameterSpec]
    return_type: str
    is_async: bool = True
    requires_context: bool = True
    
@dataclass
class ParameterSpec:
    """参数规格"""
    name: str
    type: str
    required: bool
    default: Optional[Any] = None
    description: str = ""

命令分类:

类别 命令示例 用途
文件操作 read, write, ls 文件系统交互
代码执行 run, exec, eval 代码执行
网络请求 fetch, curl HTTP 请求
系统信息 status, info 系统查询
开发工具 test, build, lint 开发工作流

2.3.4 tools.py - 工具系统

职责: 定义和管理工具端口

工具接口:

from abc import ABC, abstractmethod
from typing import Any, Dict

class Tool(ABC):
    """工具基类"""
    
    @property
    @abstractmethod
    def name(self) -> str:
        """工具名称"""
        pass
    
    @property
    @abstractmethod
    def description(self) -> str:
        """工具描述"""
        pass
    
    @abstractmethod
    async def execute(self, **kwargs) -> Any:
        """执行工具"""
        pass
    
    @abstractmethod
    def get_schema(self) -> Dict:
        """获取工具 Schema"""
        pass

class FileSystemTool(Tool):
    """文件系统工具示例"""
    
    @property
    def name(self) -> str:
        return "file_system"
    
    @property
    def description(self) -> str:
        return "File system operations (read, write, list)"
    
    async def execute(self, operation: str, path: str, **kwargs) -> Any:
        if operation == "read":
            return await self._read_file(path)
        elif operation == "write":
            return await self._write_file(path, kwargs.get("content"))
        elif operation == "list":
            return await self._list_directory(path)
        else:
            raise ValueError(f"Unknown operation: {operation}")
    
    def get_schema(self) -> Dict:
        return {
            "type": "object",
            "properties": {
                "operation": {"type": "string", "enum": ["read", "write", "list"]},
                "path": {"type": "string"},
                "content": {"type": "string"}
            },
            "required": ["operation", "path"]
        }

2.3.5 task.py - 任务管理

职责: 任务编排和执行管理

任务状态机:

┌─────────────────────────────────────────────────────────────┐
│                    任务状态机                                │
│                                                             │
│    ┌─────────┐     ┌─────────┐     ┌─────────┐             │
│    │ PENDING │────▶│ RUNNING │────▶│COMPLETED│             │
│    └─────────┘     └─────────┘     └─────────┘             │
│         │               │                                   │
│         │               │                                   │
│         ▼               ▼                                   │
│    ┌─────────┐     ┌─────────┐                             │
│    │CANCELLED│◀────│ FAILED  │                             │
│    └─────────┘     └─────────┘                             │
│                                                             │
│   状态说明:                                                 │
│   PENDING   - 等待执行                                       │
│   RUNNING   - 正在执行                                       │
│   COMPLETED - 执行完成                                       │
│   FAILED    - 执行失败                                       │
│   CANCELLED - 已取消                                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

任务定义:

@dataclass
class Task:
    """任务定义"""
    id: str
    description: str
    status: TaskStatus = TaskStatus.PENDING
    steps: List[TaskStep] = field(default_factory=list)
    context: Dict[str, Any] = field(default_factory=dict)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: Optional[datetime] = None
    
    def add_step(self, step: TaskStep) -> None:
        """添加任务步骤"""
        self.steps.append(step)
        self.updated_at = datetime.now()
    
    def get_progress(self) -> float:
        """获取任务进度"""
        if not self.steps:
            return 0.0
        completed = sum(1 for s in self.steps if s.status == TaskStatus.COMPLETED)
        return completed / len(self.steps)

@dataclass
class TaskStep:
    """任务步骤"""
    id: str
    description: str
    command: Optional[str] = None
    tool: Optional[str] = None
    status: TaskStatus = TaskStatus.PENDING
    result: Optional[Any] = None
    error: Optional[str] = None

2.3.6 query_engine.py - 查询引擎

职责: 从工作空间渲染移植摘要和查询

查询功能:

class QueryEngine:
    """查询引擎"""
    
    def __init__(self, workspace_path: Path):
        self.workspace_path = workspace_path
        self.subsystems = []
        self.modules = []
        self._load_workspace()
    
    def _load_workspace(self) -> None:
        """加载工作空间信息"""
        # 扫描 src/ 目录
        # 解析 Python 文件
        # 构建子系统和模块列表
        pass
    
    def render_summary(self) -> str:
        """渲染移植摘要"""
        total_modules = len(self.modules)
        completed = sum(1 for m in self.modules if m.status == SubsystemStatus.COMPLETE)
        verified = sum(1 for m in self.modules if m.status == SubsystemStatus.VERIFIED)
        
        summary = f"""
Claw-Code Python Port Summary
=============================

Total Modules: {total_modules}
Completed: {completed} ({completed/total_modules*100:.1f}%)
Verified: {verified} ({verified/total_modules*100:.1f}%)

Subsystems:
"""
        for subsystem in self.subsystems:
            summary += f"  - {subsystem.name}: {subsystem.progress*100:.1f}%\n"
        
        return summary
    
    def get_module(self, name: str) -> Optional[Module]:
        """获取模块信息"""
        for module in self.modules:
            if module.name == name:
                return module
        return None

2.3.7 port_manifest.py - 移植清单

职责: 管理和输出移植清单

清单输出:

def print_manifest() -> None:
    """打印工作空间清单"""
    manifest = {
        "project": "claw-code",
        "language": "Python",
        "version": "0.1.0",
        "src_directory": "src/",
        "tests_directory": "tests/",
        "modules": [
            {
                "name": "main.py",
                "purpose": "CLI entrypoint",
                "status": "complete"
            },
            {
                "name": "models.py",
                "purpose": "Data models",
                "status": "complete"
            },
            # ... 更多模块
        ],
        "parity_checkpoint": {
            "root_entry": "mirrored",
            "subsystem_names": "mirrored",
            "command_inventory": "mirrored",
            "tool_inventory": "mirrored",
            "runtime_equivalence": "in_progress"
        }
    }
    
    print(json.dumps(manifest, indent=2))

2.4 数据流和控制流

典型请求流程

┌─────────────────────────────────────────────────────────────┐
│                    请求处理流程                              │
│                                                             │
│   用户                                                        │
│    │                                                        │
│    │ 1. CLI 命令                                             │
│    ▼                                                        │
│   ┌─────────────┐                                           │
│   │   main.py   │                                           │
│   │  (解析命令)  │                                           │
│   └──────┬──────┘                                           │
│          │                                                  │
│          │ 2. 路由到对应模块                                  │
│          ▼                                                  │
│   ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│   │  commands   │  │   tools     │  │   task      │        │
│   └──────┬──────┘  └──────┬──────┘  └──────┬──────┘        │
│          │                │                │                │
│          │ 3. 使用数据模型 │                │                │
│          └───────────────┼────────────────┘                │
│                          ▼                                  │
│                   ┌─────────────┐                           │
│                   │   models    │                           │
│                   │  (数据访问)  │                           │
│                   └──────┬──────┘                           │
│                          │                                  │
│                          │ 4. 返回结果                        │
│                          ▼                                  │
│   ┌──────────────────────────────────────────────┐         │
│   │              输出到用户                        │         │
│   └──────────────────────────────────────────────┘         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2.5 与原始系统对比

架构对比

特性 原始系统 (TypeScript) Claw-Code (Python)
语言 TypeScript Python 3.10+
运行时 Node.js CPython
类型系统 静态类型 动态类型 + 类型提示
并发模型 async/await async/await
包管理 npm/pnpm pip/poetry
测试框架 Jest unittest/pytest

功能对等状态

┌─────────────────────────────────────────────────────────────┐
│                    功能对等状态                              │
│                                                             │
│   已镜像 (Mirrored):                                        │
│   ✅ 根入口文件表面                                           │
│   ✅ 顶层子系统名称                                           │
│   ✅ 命令清单                                                 │
│   ✅ 工具清单                                                 │
│                                                             │
│   进行中 (In Progress):                                     │
│   🔄 运行时等价实现                                           │
│   🔄 完整测试套件                                             │
│   🔄 文档完善                                                 │
│                                                             │
│   计划中 (Planned):                                         │
│   ⏳ Rust 移植                                                │
│   ⏳ 性能优化                                                 │
│   ⏳ 插件系统                                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2.6 设计原则

核心设计原则

原则 说明 实现方式
清洁室 不复制专有代码 从零开始重写
模块化 高内聚低耦合 清晰的模块边界
可测试 易于验证 完善的测试套件
可扩展 支持插件 清晰的接口定义
文档化 易于理解 代码注释 + 文档

代码组织原则

# 1. 单一职责原则
class FileSystemTool:
    """只负责文件系统操作"""
    pass

class NetworkTool:
    """只负责网络请求"""
    pass

# 2. 开放封闭原则
class Tool(ABC):
    """对扩展开放,对修改封闭"""
    pass

# 3. 依赖倒置原则
def execute_task(task: Task, tool_registry: ToolRegistry):
    """依赖抽象而非具体实现"""
    pass

2.7 本章总结

架构要点

  1. 分层架构: 接口层 → 核心引擎层 → 数据模型层 → 基础设施层
  2. 模块化设计: 7 个核心模块,职责清晰
  3. 数据流: CLI → 模块 → 数据模型 → 输出
  4. 对等状态: 表面结构已镜像,运行时实现进行中

关键模块

模块 职责 状态
main.py CLI 入口 ✅ 完成
models.py 数据模型 ✅ 完成
commands.py 命令系统 ✅ 完成
tools.py 工具系统 ✅ 完成
task.py 任务管理 🔄 进行中
query_engine.py 查询引擎 ✅ 完成
port_manifest.py 移植清单 ✅ 完成

下一章预告

第三章:Python 移植实现

  • 移植方法论
  • 关键技术挑战
  • 代码示例详解
  • 测试策略
posted on 2026-04-01 10:58  每天进步一点点点点点  阅读(323)  评论(0)    收藏  举报