Skip to content

SemanticVoxelProtocol/SVPDesign

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

SVP (Semantic Voxel Protocol) 项目设计稿

完整工程架构与实现指南


📋 目录

  1. 项目概述
  2. 工程划分
  3. 核心架构
  4. Package设计
  5. 实现细节
  6. 使用流程
  7. MCP生态集成
  8. Adapter设计
  9. 开发路线图
  10. 附录

项目概述

项目名称

SVP (Semantic Voxel Protocol) - 语义体素协议

核心定位

AI-Human协作编程的"智能上下文网关",通过语义体素+LOD技术,为AI提供结构化的代码认知空间。

设计哲学

Code → Voxel Space → AI Understanding
原始代码 ──▶ 语义体素空间 ──▶ AI可理解的结构化上下文

工程划分

Monorepo结构

svp/
├── packages/
│   ├── core/                    # @semanticvoxelprotocol/core
│   │   └── 核心引擎(体素化、LOD、上下文管理)
│   │
│   ├── sdk/                     # @semanticvoxelprotocol/sdk
│   │   └── TypeScript SDK(开发者使用)
│   │
│   ├── mcp-server/              # @semanticvoxelprotocol/mcp-server
│   │   └── MCP协议适配(Claude/Cursor集成)
│   │
│   ├── cli/                     # @semanticvoxelprotocol/cli
│   │   └── 命令行工具
│   │
│   ├── vscode-extension/        # VS Code扩展
│   │   └── IDE插件
│   │
│   ├── adapters/
│   │   ├── lsp-adapter/         # LSP协议适配
│   │   ├── git-adapter/         # Git集成
│   │   └── tree-sitter-adapter/ # 语法解析
│   │
│   └── shared/                  # @semanticvoxelprotocol/shared
│       └── 共享类型和工具
│
├── apps/
│   └── playground/              # 开发测试环境
│
├── docs/
│   ├── specification/           # 协议规范
│   └── api-reference/           # API文档
│
└── examples/
    ├── basic-usage/             # 基础用法示例
    └── mcp-integration/         # MCP集成示例

Package依赖关系

                    ┌─────────────────┐
                    │  vscode-ext     │
                    └────────┬────────┘
                             │
                    ┌────────▼────────┐
                    │      cli        │
                    └────────┬────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
     ┌────────▼────────┐    │    ┌─────────▼─────────┐
     │   mcp-server    │    │    │   playground      │
     └────────┬────────┘    │    └───────────────────┘
              │             │
     ┌────────▼─────────────┴────────┐
     │              sdk               │
     └───────────────┬────────────────┘
                     │
     ┌───────────────┼───────────────┐
     │               │               │
┌────▼────┐   ┌──────▼──────┐   ┌────▼────┐
│  core   │   │   shared    │   │adapters │
└─────────┘   └─────────────┘   └─────────┘

核心架构

分层架构

┌─────────────────────────────────────────────────────────────────┐
│                      Application Layer                           │
│         CLI │ VS Code Ext │ MCP Server │ Web UI                │
├─────────────────────────────────────────────────────────────────┤
│                        SDK Layer                                 │
│              VoxelClient │ ContextAPI │ QueryAPI               │
├─────────────────────────────────────────────────────────────────┤
│                       Core Engine Layer                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ Ingestion   │  │ Voxelization│  │    LOD      │             │
│  │   Engine    │  │   Engine    │  │   Manager   │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │  Context    │  │   Query     │  │    Sync     │             │
│  │ Aggregator  │  │   Engine    │  │   Manager   │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
├─────────────────────────────────────────────────────────────────┤
│                      Adapter Layer                               │
│    LSP Adapter │ Git Adapter │ Tree-sitter │ File System       │
├─────────────────────────────────────────────────────────────────┤
│                       Data Layer                                 │
│    Octree Index │ Vector DB │ Semantic Cache │ File Storage    │
└─────────────────────────────────────────────────────────────────┘

核心组件详解

1. Ingestion Engine(摄取引擎)

// packages/core/src/ingestion/engine.ts

interface IngestionConfig {
  source: {
    rootPath: string;
    include: string[];
    exclude: string[];
    gitIntegration: boolean;
  };
  context: {
    configFiles: string[];
    designDocs: string[];
    envVars: string[];
    screenshots: string[];
  };
  watch: {
    enabled: boolean;
    debounceMs: number;
  };
}

class IngestionEngine {
  constructor(private config: IngestionConfig) {}
  
  // 扫描源码文件
  async scanSource(): Promise<SourceFile[]> {
    // 使用glob扫描文件
    // 排除node_modules等
  }
  
  // 加载外部上下文
  async loadExternalContext(): Promise<ExternalContext> {
    // 读取.svp/config.yaml
    // 加载设计文档
    // 解析环境变量
  }
  
  // 监听文件变化
  watchChanges(callback: (event: FileEvent) => void): void {
    // 使用chokidar监听
    // 防抖处理
  }
}

2. Voxelization Engine(体素化引擎)

// packages/core/src/voxelization/engine.ts

interface SemanticVoxel {
  id: string;
  position: { x: number; y: number; z: number };
  nodeType: ASTNodeType;
  semanticRole: SemanticRole;
  dataType?: string;
  scopeLevel: number;
  parent?: VoxelRef;
  children: VoxelRef[];
  references: VoxelRef[];
  sourceLocation: SourceLocation;
  codeSnippet: string;
  visual: VisualProperties;
}

class VoxelizationEngine {
  constructor(
    private parser: TreeSitterAdapter,
    private lspAdapter: LSPAdapter
  ) {}
  
  // 将AST转换为语义体素
  async voxelize(ast: ASTNode[]): Promise<SemanticVoxel[]> {
    // 遍历AST节点
    // 为每个节点创建体素
    // 计算空间坐标
  }
  
  // 构建八叉树索引
  buildOctree(voxels: SemanticVoxel[]): OctreeIndex {
    // 使用稀疏八叉树
    // 支持快速空间查询
  }
  
  // 建立关系图谱
  buildRelationGraph(voxels: SemanticVoxel[]): RelationGraph {
    // 调用关系
    // 数据流关系
    // 继承关系
  }
}

3. LOD Manager(LOD管理器)

// packages/core/src/lod/manager.ts

enum LODLevel {
  ARCHITECTURE = 5,   // 架构意图
  MODULE = 4,         // 模块契约
  ALGORITHM = 3,      // 算法逻辑
  IMPLEMENTATION = 2, // 实现细节
  SYNTAX = 1          // 语法结构
}

interface LODProfile {
  level: LODLevel;
  includeProperties: string[];
  excludeProperties: string[];
  renderMode: 'voxel' | 'cluster' | 'graph';
}

class LODManager {
  // 预计算每个体素的LOD级别
  precomputeLODs(voxel: SemanticVoxel): Map<LODLevel, LODVoxel> {
    // LOD-5: 只保留接口定义
    // LOD-4: 保留函数签名和关键注释
    // LOD-3: 保留控制流结构
    // LOD-2: 保留完整实现
    // LOD-1: 保留语法细节
  }
  
  // 根据上下文选择LOD
  selectLOD(context: TaskContext): LODLevel {
    // taskType: navigation/debugging/refactoring
    // userExpertise: novice/intermediate/expert
    // timeConstraint: quick/normal/deep
  }
  
  // LOD平滑过渡
  async transitionLOD(
    from: LODLevel,
    to: LODLevel,
    focusVoxel?: VoxelRef
  ): Promise<TransitionResult> {
    // 动画过渡
    // 保持上下文连续性
  }
}

4. Context Aggregator(上下文聚合器)

// packages/core/src/context/aggregator.ts

interface ContextSnapshot {
  codeContext: {
    voxels: SemanticVoxel[];
    relations: RelationEdge[];
    lod: LODLevel;
  };
  externalContext: {
    designDocs: DesignDoc[];
    envVars: EnvVar[];
    screenshots: Screenshot[];
  };
  meta: {
    projectName: string;
    language: string;
    totalFiles: number;
    totalVoxels: number;
    coverage: number;
    tokenUsage: TokenUsage;
  };
}

class ContextAggregator {
  constructor(
    private voxelEngine: VoxelizationEngine,
    private lodManager: LODManager,
    private queryEngine: QueryEngine
  ) {}
  
  // 分析任务意图
  analyzeIntent(query: string): TaskIntent {
    // 关键词提取
    // 实体识别
    // 任务分类
  }
  
  // 组装上下文
  async buildContext(
    query: string,
    maxTokens: number
  ): Promise<ContextSnapshot> {
    // 1. 分析意图
    // 2. 搜索相关体素
    // 3. 选择LOD
    // 4. 加载外部上下文
    // 5. 管理Token预算
  }
  
  // Token预算管理
  manageTokenBudget(
    context: ContextSnapshot,
    maxTokens: number
  ): TrimmedContext {
    // 优先级排序
    // 裁剪低优先级内容
    // 确保核心上下文保留
  }
}

5. Query Engine(查询引擎)

// packages/core/src/query/engine.ts

interface QueryOptions {
  keywords?: string[];
  semanticType?: string;
  lod?: LODLevel;
  boundingBox?: BoundingBox;
  limit?: number;
}

class QueryEngine {
  constructor(private octreeIndex: OctreeIndex) {}
  
  // 语义搜索
  async semanticSearch(query: string): Promise<VoxelRef[]> {
    // 向量化查询
    // 相似度计算
    // 返回相关体素
  }
  
  // 空间查询
  async spatialQuery(
    center: Position,
    radius: number
  ): Promise<VoxelRef[]> {
    // 八叉树范围查询
  }
  
  // 关系查询
  async relationQuery(
    voxelId: string,
    relationType: RelationType
  ): Promise<VoxelRef[]> {
    // 调用图遍历
    // 数据流追踪
  }
}

Package设计

1. @semanticvoxelprotocol/core

package.json

{
  "name": "@semanticvoxelprotocol/core",
  "version": "0.1.0",
  "description": "SVP核心引擎",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc",
    "test": "jest",
    "lint": "eslint src/**/*.ts"
  },
  "dependencies": {
    "@semanticvoxelprotocol/shared": "workspace:*",
    "tree-sitter": "^0.21.0",
    "chokidar": "^3.6.0",
    "yaml": "^2.4.0"
  },
  "devDependencies": {
    "typescript": "^5.4.0",
    "@types/node": "^20.11.0"
  }
}

目录结构

core/
├── src/
│   ├── index.ts                    # 入口
│   ├── ingestion/
│   │   ├── engine.ts
│   │   ├── scanner.ts
│   │   └── watcher.ts
│   ├── voxelization/
│   │   ├── engine.ts
│   │   ├── coordinate.ts
│   │   └── properties.ts
│   ├── lod/
│   │   ├── manager.ts
│   │   ├── profiles.ts
│   │   └── transition.ts
│   ├── context/
│   │   ├── aggregator.ts
│   │   ├── intent.ts
│   │   └── budget.ts
│   ├── query/
│   │   ├── engine.ts
│   │   ├── semantic.ts
│   │   └── spatial.ts
│   ├── storage/
│   │   ├── octree.ts
│   │   ├── cache.ts
│   │   └── persistence.ts
│   └── utils/
│       ├── logger.ts
│       └── errors.ts
├── tests/
│   └── *.test.ts
├── package.json
└── tsconfig.json

2. @semanticvoxelprotocol/sdk

package.json

{
  "name": "@semanticvoxelprotocol/sdk",
  "version": "0.1.0",
  "description": "SVP TypeScript SDK",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc",
    "test": "jest"
  },
  "dependencies": {
    "@semanticvoxelprotocol/core": "workspace:*",
    "@semanticvoxelprotocol/shared": "workspace:*",
    "axios": "^1.6.0",
    "ws": "^8.16.0"
  }
}

核心API

// packages/sdk/src/client.ts

export class SVPClient {
  constructor(options: SVPClientOptions) {
    // 初始化连接
  }
  
  // 获取上下文快照
  async getContext(query: string): Promise<ContextSnapshot> {
    // 调用核心引擎
  }
  
  // 查询体素
  async queryVoxels(options: QueryOptions): Promise<SemanticVoxel[]> {
    // 空间/语义查询
  }
  
  // 切换LOD
  async switchLOD(level: LODLevel): Promise<void> {
    // LOD切换
  }
  
  // 监听变化
  onChange(callback: (event: ChangeEvent) => void): void {
    // WebSocket实时同步
  }
}

3. @semanticvoxelprotocol/mcp-server

package.json

{
  "name": "@semanticvoxelprotocol/mcp-server",
  "version": "0.1.0",
  "description": "SVP MCP Server",
  "bin": {
    "svp-mcp": "dist/server.js"
  },
  "scripts": {
    "build": "tsc",
    "start": "node dist/server.js"
  },
  "dependencies": {
    "@semanticvoxelprotocol/core": "workspace:*",
    "@modelcontextprotocol/sdk": "^0.5.0"
  }
}

MCP Server实现

// packages/mcp-server/src/server.ts

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

class SVP_MCPServer {
  private server: Server;
  private core: SVPCore;
  
  constructor() {
    this.server = new Server({
      name: 'svp-mcp-server',
      version: '0.1.0'
    }, {
      capabilities: {
        resources: {},
        tools: {}
      }
    });
    
    this.setupHandlers();
  }
  
  private setupHandlers() {
    // Resources: 暴露体素地图
    this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
      return {
        resources: [
          {
            uri: 'svp://project/voxels',
            name: 'Project Voxel Map',
            mimeType: 'application/vnd.svp.voxel+json'
          },
          {
            uri: 'svp://project/context',
            name: 'Current Context',
            mimeType: 'application/vnd.svp.context+json'
          }
        ]
      };
    });
    
    // Tools: 提供LOD切换、查询等功能
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'switch_lod',
            description: 'Switch to a different LOD level',
            inputSchema: {
              type: 'object',
              properties: {
                level: {
                  type: 'number',
                  enum: [1, 2, 3, 4, 5],
                  description: 'LOD level'
                }
              },
              required: ['level']
            }
          },
          {
            name: 'query_voxels',
            description: 'Query voxels by semantic criteria',
            inputSchema: {
              type: 'object',
              properties: {
                keywords: {
                  type: 'array',
                  items: { type: 'string' }
                },
                semanticType: { type: 'string' },
                lod: { type: 'number' }
              }
            }
          },
          {
            name: 'get_context',
            description: 'Get context snapshot for a query',
            inputSchema: {
              type: 'object',
              properties: {
                query: { type: 'string' },
                maxTokens: { type: 'number' }
              },
              required: ['query']
            }
          }
        ]
      };
    });
  }
  
  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
  }
}

// 启动服务器
const server = new SVP_MCPServer();
server.run();

4. @semanticvoxelprotocol/cli

package.json

{
  "name": "@semanticvoxelprotocol/cli",
  "version": "0.1.0",
  "description": "SVP CLI工具",
  "bin": {
    "svp": "dist/cli.js"
  },
  "scripts": {
    "build": "tsc"
  },
  "dependencies": {
    "@semanticvoxelprotocol/core": "workspace:*",
    "commander": "^12.0.0",
    "chalk": "^5.3.0",
    "ora": "^8.0.0"
  }
}

CLI实现

// packages/cli/src/cli.ts

import { Command } from 'commander';
import chalk from 'chalk';

const program = new Command();

program
  .name('svp')
  .description('Semantic Voxel Protocol CLI')
  .version('0.1.0');

// svp init
program
  .command('init')
  .description('Initialize SVP for current project')
  .option('-l, --language <lang>', 'Project language', 'typescript')
  .action(async (options) => {
    console.log(chalk.blue('Initializing SVP...'));
    // 创建.svp/目录
    // 生成默认配置
    // 首次体素化
  });

// svp voxelize
program
  .command('voxelize')
  .description('Voxelize the codebase')
  .option('-w, --watch', 'Watch for changes')
  .action(async (options) => {
    console.log(chalk.blue('Voxelizing...'));
    // 扫描源码
    // 生成体素
    // 构建索引
  });

// svp serve
program
  .command('serve')
  .description('Start SVP service')
  .option('-p, --port <port>', 'Port number', '8080')
  .action(async (options) => {
    console.log(chalk.blue(`Starting SVP service on port ${options.port}...`));
    // 启动HTTP/gRPC服务
    // 支持多客户端连接
  });

// svp query
program
  .command('query <query>')
  .description('Query the voxel space')
  .option('-l, --lod <level>', 'LOD level', '4')
  .action(async (query, options) => {
    // 执行查询
    // 显示结果
  });

program.parse();

实现细节

1. 类型定义(shared包)

// packages/shared/src/types.ts

// 核心体素类型
export interface SemanticVoxel {
  id: string;
  position: Vector3;
  nodeType: ASTNodeType;
  semanticRole: SemanticRole;
  dataType?: string;
  scopeLevel: number;
  parent?: VoxelRef;
  children: VoxelRef[];
  references: VoxelRef[];
  sourceLocation: SourceLocation;
  codeSnippet: string;
  visual: VisualProperties;
  lodProfiles: Map<LODLevel, LODVoxel>;
}

// LOD级别
export enum LODLevel {
  SYNTAX = 1,
  IMPLEMENTATION = 2,
  ALGORITHM = 3,
  MODULE = 4,
  ARCHITECTURE = 5
}

// 上下文快照
export interface ContextSnapshot {
  codeContext: {
    voxels: SemanticVoxel[];
    relations: RelationEdge[];
    lod: LODLevel;
  };
  externalContext: {
    designDocs: DesignDoc[];
    envVars: EnvVar[];
    screenshots: Screenshot[];
  };
  meta: ContextMeta;
}

// 查询选项
export interface QueryOptions {
  keywords?: string[];
  semanticType?: ASTNodeType;
  lod?: LODLevel;
  boundingBox?: BoundingBox;
  limit?: number;
}

// 任务上下文
export interface TaskContext {
  taskType: TaskType;
  userExpertise: UserExpertise;
  timeConstraint: TimeConstraint;
  focusArea?: VoxelRef[];
  history: NavigationPath[];
}

2. 八叉树实现

// packages/core/src/storage/octree.ts

export class OctreeNode {
  voxels: SemanticVoxel[] = [];
  children: OctreeNode[] | null = null;
  
  constructor(
    public bounds: BoundingBox,
    public depth: number,
    public maxDepth: number = 8
  ) {}
  
  insert(voxel: SemanticVoxel): void {
    if (this.depth === this.maxDepth) {
      this.voxels.push(voxel);
      return;
    }
    
    if (!this.children) {
      this.subdivide();
    }
    
    const childIndex = this.getChildIndex(voxel.position);
    this.children![childIndex].insert(voxel);
  }
  
  queryRange(range: BoundingBox): SemanticVoxel[] {
    if (!this.intersects(range)) {
      return [];
    }
    
    let results = this.voxels.filter(v => range.contains(v.position));
    
    if (this.children) {
      for (const child of this.children) {
        results = results.concat(child.queryRange(range));
      }
    }
    
    return results;
  }
  
  private subdivide(): void {
    // 创建8个子节点
  }
  
  private getChildIndex(position: Vector3): number {
    // 计算子节点索引
  }
  
  private intersects(range: BoundingBox): boolean {
    // AABB相交测试
  }
}

使用流程

安装

# 全局安装CLI
npm install -g @semanticvoxelprotocol/cli

# 或者本地安装
npm install --save-dev @semanticvoxelprotocol/cli

# 安装SDK(用于程序化访问)
npm install @semanticvoxelprotocol/sdk

初始化项目

# 进入项目目录
cd my-project

# 初始化SVP
svp init

# 交互式配置
# ? Project language: TypeScript
# ? Include git history: Yes
# ? LOD default level: 4 (Module Contract)
# ? Token budget: 8000

# 生成配置文件
# .svp/config.yaml

配置文件示例

# .svp/config.yaml
project:
  name: "my-project"
  language: "typescript"
  description: "A task management application"

source:
  root: "./src"
  include:
    - "src/**/*"
    - "lib/**/*"
  exclude:
    - "node_modules"
    - "dist"
    - "**/*.test.ts"
    - "**/*.spec.ts"
  git:
    enabled: true
    maxHistoryDepth: 100

context:
  designDocs:
    - path: "docs/architecture.md"
      description: "System architecture"
    - path: "docs/api-design.md"
      description: "API design document"
  
  envVars:
    - path: ".env.example"
      description: "Environment template"
  
  screenshots:
    - path: "assets/architecture.png"
      description: "Architecture diagram"
      relatedTo: ["src/core", "src/api"]

lod:
  defaultLevel: 4
  overrides:
    - path: "src/core/**"
      level: 2
    - path: "src/utils/**"
      level: 5

exposure:
  virtualFolders:
    "/core":
      physicalPaths: ["src/core/**"]
      description: "Core business logic"
    "/api":
      physicalPaths: ["src/api/**"]
      description: "API endpoints"
  
  restrictedPaths:
    - "src/secrets/**"
    - ".env.production"
  
  tokenBudget:
    default: 8000
    max: 32000

sync:
  reverseSync:
    enabled: true
    highlightActiveVoxels: true
    showArchitectureUpdates: true
  
  realtime:
    enabled: true
    debounceMs: 500

启动服务

# 启动本地服务
svp serve

# 选项
svp serve --port 8080 --watch

# 输出
# ✓ Loaded configuration from .svp/config.yaml
# ✓ Indexed 1,247 files
# ✓ Generated 45,832 voxels
# ✓ Built octree index (depth: 8)
# ✓ SVP service running on http://localhost:8080

使用SDK

import { SVPClient } from '@semanticvoxelprotocol/sdk';

const client = new SVPClient({
  endpoint: 'http://localhost:8080',
  project: 'my-project'
});

// 获取上下文
const context = await client.getContext({
  query: '实现用户登录功能',
  maxTokens: 8000
});

console.log(context.codeContext.voxels);
console.log(context.externalContext.designDocs);

// 查询体素
const voxels = await client.queryVoxels({
  keywords: ['auth', 'login'],
  semanticType: 'function',
  lod: 4
});

// 切换LOD
await client.switchLOD(LODLevel.IMPLEMENTATION);

// 监听变化
client.onChange((event) => {
  console.log('Code changed:', event.file);
  console.log('Affected voxels:', event.voxels);
});

MCP集成

// claude_desktop_config.json
{
  "mcpServers": {
    "semantic-voxel": {
      "command": "npx",
      "args": ["-y", "@semanticvoxelprotocol/mcp-server"],
      "env": {
        "SVP_PROJECT_PATH": "/path/to/your/project"
      }
    }
  }
}

现在Claude可以:

  • 自动获取项目上下文
  • 导航语义体素空间
  • 动态切换LOD级别

MCP生态集成

生态系统定位

┌─────────────────────────────────────────────────────────────┐
│                    AI编程协议生态                            │
├─────────────────────────────────────────────────────────────┤
│  A2A (Agent-to-Agent)                                       │
│  - Agent间协作通信                                          │
├─────────────────────────────────────────────────────────────┤
│  MCP (Model Context Protocol)                               │
│  - 工具调用、资源访问                                        │
│  - SVP作为MCP Server暴露体素服务                            │
├─────────────────────────────────────────────────────────────┤
│  ★ SVP (Semantic Voxel Protocol)                           │
│  ★ 代码语义表示、LOD管理                                    │
│  ★ 共享认知空间                                             │
├─────────────────────────────────────────────────────────────┤
│  LSP (Language Server Protocol)                             │
│  - 语法分析、符号解析                                        │
└─────────────────────────────────────────────────────────────┘

SVP MCP Server能力

// Resources(资源)
{
  'svp://{project}/voxels': '体素地图',
  'svp://{project}/context': '当前上下文',
  'svp://{project}/architecture': '架构视图',
  'svp://{project}/relations': '关系图谱'
}

// Tools(工具)
{
  'switch_lod': '切换LOD级别',
  'query_voxels': '查询体素',
  'get_context': '获取上下文快照',
  'navigate_relation': '导航关系图谱',
  'highlight_voxel': '高亮体素'
}

// Prompts(提示模板)
{
  'code_review': '代码审查模板',
  'refactoring': '重构建议模板',
  'architecture_review': '架构审查模板'
}

与其他MCP Server协作

┌─────────────────────────────────────────────────────────────┐
│                      MCP生态系统                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   ┌─────────────┐      ┌─────────────┐      ┌────────────┐ │
│   │  Filesystem │      │    GitHub   │      │  Database  │ │
│   │   Server    │      │   Server    │      │   Server   │ │
│   └──────┬──────┘      └──────┬──────┘      └─────┬──────┘ │
│          │                    │                   │        │
│          └────────────────────┼───────────────────┘        │
│                               │                            │
│                      ┌────────▼────────┐                   │
│                      │   MCP Host      │                   │
│                      │ (Claude/Cursor) │                   │
│                      └────────┬────────┘                   │
│                               │                            │
│                      ┌────────▼────────┐                   │
│                      │   SVP Server    │                   │
│                      │  (代码语义服务)  │                   │
│                      └─────────────────┘                   │
│                                                             │
│   Claude: "我需要修改用户认证模块"                          │
│   ↓                                                         │
│   SVP Server: 提供相关体素(LOD-4模块视图)                  │
│   ↓                                                         │
│   Filesystem Server: 读取/写入文件                          │
│   ↓                                                         │
│   GitHub Server: 创建PR                                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Adapter设计

1. LSP Adapter

// packages/adapters/lsp-adapter/src/index.ts

export class LSPAdapter {
  private connection: Connection;
  
  constructor(private serverPath: string) {}
  
  async initialize(): Promise<void> {
    // 启动LSP服务器
    // 建立连接
  }
  
  // 获取符号信息
  async getSymbols(filePath: string): Promise<SymbolInformation[]> {
    const response = await this.connection.sendRequest(
      'textDocument/documentSymbol',
      { textDocument: { uri: filePath } }
    );
    return response;
  }
  
  // 获取类型定义
  async getTypeDefinition(
    filePath: string,
    position: Position
  ): Promise<Location[]> {
    const response = await this.connection.sendRequest(
      'textDocument/typeDefinition',
      {
        textDocument: { uri: filePath },
        position
      }
    );
    return response;
  }
  
  // 获取引用
  async getReferences(
    filePath: string,
    position: Position
  ): Promise<Location[]> {
    const response = await this.connection.sendRequest(
      'textDocument/references',
      {
        textDocument: { uri: filePath },
        position,
        context: { includeDeclaration: true }
      }
    );
    return response;
  }
}

2. Git Adapter

// packages/adapters/git-adapter/src/index.ts

export class GitAdapter {
  constructor(private repoPath: string) {}
  
  // 获取文件历史
  async getFileHistory(filePath: string): Promise<Commit[]> {
    const result = await execAsync(
      `git log --follow --format="%H|%an|%ad|%s" -- "${filePath}"`,
      { cwd: this.repoPath }
    );
    return this.parseLog(result.stdout);
  }
  
  // 获取变更记录
  async getChanges(filePath: string): Promise<Change[]> {
    const result = await execAsync(
      `git log -p -- "${filePath}"`,
      { cwd: this.repoPath }
    );
    return this.parseDiff(result.stdout);
  }
  
  // 获取作者信息
  async getAuthors(filePath: string): Promise<Author[]> {
    const result = await execAsync(
      `git log --format="%an" -- "${filePath}" | sort | uniq -c | sort -rn`,
      { cwd: this.repoPath }
    );
    return this.parseAuthors(result.stdout);
  }
}

3. Tree-sitter Adapter

// packages/adapters/tree-sitter-adapter/src/index.ts

import Parser from 'tree-sitter';
import TypeScript from 'tree-sitter-typescript';

export class TreeSitterAdapter {
  private parser: Parser;
  private languageMap: Map<string, Parser.Language>;
  
  constructor() {
    this.parser = new Parser();
    this.languageMap = new Map([
      ['typescript', TypeScript.typescript],
      ['tsx', TypeScript.tsx],
      ['javascript', TypeScript.javascript]
    ]);
  }
  
  parse(code: string, language: string): Parser.Tree {
    const lang = this.languageMap.get(language);
    if (!lang) {
      throw new Error(`Unsupported language: ${language}`);
    }
    this.parser.setLanguage(lang);
    return this.parser.parse(code);
  }
  
  // 提取函数定义
  extractFunctions(tree: Parser.Tree): FunctionNode[] {
    const query = new Parser.Query(
      this.parser.getLanguage(),
      `
      (function_declaration
        name: (identifier) @name
        parameters: (formal_parameters) @params
        body: (statement_block) @body) @function
      
      (arrow_function
        parameters: (formal_parameters) @params
        body: (_) @body) @function
      `
    );
    
    const matches = query.matches(tree.rootNode);
    return matches.map(match => this.parseFunctionNode(match));
  }
  
  // 提取类定义
  extractClasses(tree: Parser.Tree): ClassNode[] {
    // 类似实现
  }
}

开发路线图

Phase 1: Foundation (Month 1-2)

  • 项目脚手架搭建
  • Core包基础实现
    • Ingestion Engine
    • Voxelization Engine
    • LOD Manager
    • Context Aggregator
  • Shared包类型定义
  • CLI基础命令
  • SDK基础API
  • 单元测试覆盖

Phase 2: Integration (Month 3-4)

  • MCP Server实现
  • LSP Adapter
  • Git Adapter
  • Tree-sitter Adapter
  • VS Code Extension MVP
  • 文档网站

Phase 3: Ecosystem (Month 5-6)

  • 多语言支持(Python, Go, Rust)
  • JetBrains Plugin
  • Web UI
  • 性能优化
  • 社区示例

Phase 4: Standardization (Month 7+)

  • 协议规范完善
  • W3C/Linux Foundation提交
  • 企业级功能
  • Cloud Service

附录

A. 技术栈

层级 技术
语言 TypeScript 5.4+
运行时 Node.js 20+
构建 tsc + esbuild
测试 Jest
包管理 pnpm workspaces
代码质量 ESLint + Prettier

B. 目录结构规范

packages/{name}/
├── src/
│   ├── index.ts          # 入口文件
│   ├── {feature}/        # 功能模块
│   │   ├── index.ts
│   │   └── *.ts
│   └── utils/            # 工具函数
├── tests/
│   └── *.test.ts
├── package.json
├── tsconfig.json
└── README.md

C. 命名规范

  • Package: @semanticvoxelprotocol/{name}
  • Class: PascalCase
  • Interface: PascalCase
  • Function: camelCase
  • Constant: UPPER_SNAKE_CASE
  • Type: PascalCase

D. 版本策略

  • 遵循SemVer
  • Alpha: 0.x.x-alpha.x
  • Beta: 0.x.x-beta.x
  • RC: 0.x.x-rc.x
  • Stable: 1.x.x

About

Design of Semantic Voxel Architecture

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors