# Design Document: aitool CLI

## Overview

aitool 是一个基于 Node.js + TypeScript 开发的命令行工具，用于快速初始化工程项目。该工具采用模块化设计，使用 Commander.js 处理命令行参数，使用 Inquirer.js 实现交互式提示，使用 fs-extra 进行文件操作。

## Architecture

```mermaid
graph TB
    subgraph CLI Layer
        A[aitool CLI Entry] --> B[Commander.js]
        B --> C[Version Command]
        B --> D[Init Command]
        B --> E[Help Command]
        B --> K[UpdateRules Command]
    end
    
    subgraph Core Layer
        D --> F[Template Manager]
        K --> L[Rules Manager]
        F --> G[Template Selector - Inquirer]
        F --> H[File Copier]
        L --> M[Rules Scanner]
        L --> N[Rules Comparator]
    end
    
    subgraph Data Layer
        H --> I[template/uniapp]
        H --> J[template/uniappx]
        M --> O[.cursor/rules]
        M --> P[.kiro/steering]
    end
```

## Components and Interfaces

### 1. CLI Entry Point (src/index.ts)

主入口文件，负责注册所有命令和配置 Commander.js。

```typescript
interface CLIConfig {
  name: string;
  version: string;
  description: string;
}
```

### 2. Version Command (src/commands/version.ts)

处理版本查看命令。

```typescript
function showVersion(): void;
```

### 3. Init Command (src/commands/init.ts)

处理项目初始化命令，包含交互式模板选择。

```typescript
interface TemplateChoice {
  name: string;
  value: string;
  description: string;
}

async function initProject(): Promise<void>;
```

### 4. Template Manager (src/utils/templateManager.ts)

管理模板的核心模块，负责模板列表获取和文件复制。

```typescript
interface TemplateInfo {
  name: string;
  path: string;
  description: string;
}

function getAvailableTemplates(): TemplateInfo[];
function copyTemplate(templateName: string, targetDir: string): Promise<void>;
function templateExists(templateName: string): boolean;
```

### 5. UpdateRules Command (src/commands/updateRules.ts)

处理规则文件同步命令，包含交互式模板选择和规则文件对比更新。

```typescript
interface RulesSyncResult {
  added: string[];      // 新增的文件列表
  updated: string[];    // 更新的文件列表
  unchanged: string[];  // 未变更的文件列表
}

async function updateRules(): Promise<void>;
```

### 6. Rules Manager (src/utils/rulesManager.ts)

管理规则文件的核心模块，负责规则文件扫描、对比和同步。

```typescript
interface RuleFile {
  relativePath: string;  // 相对路径（如 .cursor/rules/xxx.md）
  absolutePath: string;  // 绝对路径
  content: string;       // 文件内容
  size: number;          // 内容长度
}

interface RulesDiff {
  toAdd: RuleFile[];     // 需要新增的文件
  toUpdate: RuleFile[];  // 需要更新的文件
  unchanged: RuleFile[]; // 无需变更的文件
}

// 规则目录配置
const RULES_DIRS = [
  '.cursor/rules',
  '.kiro/steering'
];

// 支持的规则文件扩展名
const RULES_EXTENSIONS = ['.md', '.mdc'];

function scanRulesFiles(baseDir: string): Promise<RuleFile[]>;
function compareRules(templateRules: RuleFile[], projectRules: RuleFile[]): RulesDiff;
function syncRules(templateName: string, targetDir: string): Promise<RulesSyncResult>;
function getTemplateRulesPath(templateName: string): string;
```

## Data Models

### Template Configuration

```typescript
// 模板配置结构
interface TemplateConfig {
  templates: {
    [key: string]: {
      name: string;
      description: string;
      folder: string;
    };
  };
}

// 默认模板配置
const defaultTemplates: TemplateConfig = {
  templates: {
    uniapp: {
      name: "uniapp",
      description: "UniApp 跨平台应用工程模板",
      folder: "uniapp"
    },
    uniappx: {
      name: "uniappx",
      description: "UniApp X 扩展版工程模板",
      folder: "uniappx"
    }
  }
};
```

## Project Structure

```
aitool/
├── src/
│   ├── index.ts              # CLI 入口
│   ├── commands/
│   │   ├── version.ts        # 版本命令
│   │   ├── init.ts           # 初始化命令
│   │   └── updateRules.ts    # 规则同步命令
│   ├── utils/
│   │   ├── templateManager.ts # 模板管理器
│   │   └── rulesManager.ts    # 规则管理器
│   └── errors/
│       └── index.ts          # 错误类型定义
├── template/
│   ├── uniapp/               # uniapp 模板
│   │   └── ...
│   └── uniappx/              # uniappx 模板
│       ├── .cursor/rules/    # Cursor 规则文件
│       ├── .kiro/steering/   # Kiro 规则文件
│       └── ...
├── package.json
├── tsconfig.json
└── README.md
```

## Dependencies

| Package | Purpose |
|---------|---------|
| commander | 命令行参数解析 |
| inquirer | 交互式命令行提示 |
| fs-extra | 增强的文件系统操作 |
| chalk | 终端文字样式 |
| typescript | TypeScript 编译 |



## Correctness Properties

*A property is a characteristic or behavior that should hold true across all valid executions of a system—essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*

### Property 1: Version Consistency

*For any* execution of the CLI version command, the displayed version string SHALL match exactly the version field in package.json.

**Validates: Requirements 1.3**

### Property 2: Template Availability

*For any* call to get available templates, the result SHALL contain at least "uniapp" and "uniappx" as valid template options.

**Validates: Requirements 2.2, 3.2**

### Property 3: Template Copy Integrity

*For any* valid template name and target directory, after copying the template, the target directory SHALL contain all files and folders that exist in the source template directory with identical content.

**Validates: Requirements 2.3**

### Property 4: Rules Sync Correctness

*For any* template with rules files and any project directory, after executing updateRules:
- All rules files that exist in the template but not in the project SHALL be copied to the project
- All rules files where template content length > project content length SHALL be overwritten
- All rules files where template content length <= project content length SHALL remain unchanged

**Validates: Requirements 5.3, 5.4, 5.5, 5.6**

## Error Handling

| Scenario | Error Type | User Message |
|----------|------------|--------------|
| Template not found | TemplateNotFoundError | "模板 '{name}' 不存在，请选择有效的模板" |
| Target directory not writable | FileSystemError | "无法写入目标目录，请检查权限" |
| Template folder missing | ConfigurationError | "模板文件夹不存在，请重新安装 CLI 工具" |
| No rules in template | RulesNotFoundError | "模板 '{name}' 中没有规则文件" |

## Testing Strategy

### Unit Tests

使用 Jest 作为测试框架，测试以下场景：

1. **Version Command Tests**
   - 验证 `-v` 和 `--version` 输出版本号
   - 验证版本号格式正确

2. **Template Manager Tests**
   - 验证 `getAvailableTemplates()` 返回正确的模板列表
   - 验证 `templateExists()` 正确判断模板是否存在
   - 验证 `copyTemplate()` 在模板不存在时抛出错误

3. **Help Command Tests**
   - 验证帮助信息包含所有命令

### Property-Based Tests

使用 fast-check 进行属性测试：

1. **Property 1: Version Consistency**
   - 配置：100 次迭代
   - 标签：**Feature: aitool-cli, Property 1: Version Consistency**

2. **Property 2: Template Availability**
   - 配置：100 次迭代
   - 标签：**Feature: aitool-cli, Property 2: Template Availability**

3. **Property 3: Template Copy Integrity**
   - 配置：100 次迭代
   - 标签：**Feature: aitool-cli, Property 3: Template Copy Integrity**
