7 Commits

Author SHA1 Message Date
moyin
a147883e05 docs:添加架构重构文档
- 新增 ARCHITECTURE_REFACTORING.md 文档
- 记录项目架构重构计划和进度
2026-01-14 13:17:53 +08:00
moyin
cf431c210a docs:补充 Gateway 层架构规范检查说明
- 新增 Gateway 层职责定义和检查规范
- 添加 Gateway 层协议处理示例代码
- 补充 Gateway 层依赖关系和文件类型检查
- 完善 4 层架构说明(Gateway、Business、Core、Common)
- 增加 Gateway 层常见违规示例
2026-01-14 13:17:44 +08:00
moyin
41c33d6159 docs:完善 NestJS 框架文件命名规范说明
- 详细说明 NestJS 文件命名规则(snake_case + 点分隔类型标识符)
- 添加正确和错误的命名示例对比
- 补充所有 NestJS 文件类型标识符列表
- 增加常见错误判断方法说明
2026-01-14 13:17:23 +08:00
moyin
8bcd22ea50 docs:将 AI 代码检查指南翻译为英文
- 将主要内容从中文翻译为英文
- 添加用户信息配置脚本使用说明
- 优化文档结构和可读性
- 保持原有检查流程和规范不变
2026-01-14 13:17:12 +08:00
moyin
43874892b7 feat:添加 AI 代码检查用户信息配置工具
- 新增 setup-user-info.js 脚本
- 自动获取当前日期并提示输入用户名
- 生成 me.config.json 配置文件供 AI 检查步骤使用
- 简化 AI 代码检查流程的用户信息收集
2026-01-14 13:17:02 +08:00
moyin
f1dd8cd14a style:优化贡献者文档格式
- 调整贡献者顺序展示
- 优化贡献统计表格排列
- 改善文档可读性
2026-01-14 13:16:53 +08:00
moyin
f9a79461a0 config:更新 .gitignore 配置
- 添加 docs/ai-reading/me.config.json 到忽略列表
- 优化配置文件结构
2026-01-14 13:16:44 +08:00
7 changed files with 1001 additions and 318 deletions

3
.gitignore vendored
View File

@@ -48,4 +48,5 @@ redis-data/
.kiro/
config/
docs/merge-requests
docs/merge-requests
docs/ai-reading/me.config.json

View File

@@ -0,0 +1,295 @@
# 架构重构文档
## 重构目标
将现有的混合架构重构为清晰的4层架构实现更好的关注点分离和代码组织。
## 架构对比
### 重构前
```
src/
├── business/auth/ # 混合了Gateway和Business职责
│ ├── login.controller.ts # HTTP协议处理
│ ├── login.service.ts # 业务逻辑
│ ├── jwt_auth.guard.ts # 认证守卫
│ └── dto/ # 数据传输对象
└── core/login_core/ # 核心层
└── login_core.service.ts # 数据访问和基础设施
```
### 重构后
```
src/
├── gateway/auth/ # 网关层(新增)
│ ├── login.controller.ts # HTTP协议处理
│ ├── register.controller.ts # HTTP协议处理
│ ├── jwt_auth.guard.ts # 认证守卫
│ ├── dto/ # 数据传输对象
│ └── auth.gateway.module.ts # 网关模块
├── business/auth/ # 业务层(精简)
│ ├── login.service.ts # 登录业务逻辑
│ ├── register.service.ts # 注册业务逻辑
│ └── auth.module.ts # 业务模块
└── core/login_core/ # 核心层(不变)
└── login_core.service.ts # 数据访问和基础设施
```
## 4层架构说明
### 1. Transport Layer传输层- 可选
**位置**`src/transport/`
**职责**
- 底层网络通信和连接管理
- WebSocket服务器、TCP/UDP服务器
- 原生Socket连接池管理
**说明**对于HTTP应用NestJS已经提供了传输层无需额外实现。对于WebSocket等特殊协议可以在此层实现。
### 2. Gateway Layer网关层
**位置**`src/gateway/`
**职责**
- HTTP协议处理和请求响应
- 数据验证DTO
- 路由管理
- 认证守卫
- 错误转换(业务错误 → HTTP状态码
- API文档
**原则**
- ✅ 只做协议转换,不做业务逻辑
- ✅ 使用DTO进行数据验证
- ✅ 统一的错误处理
- ❌ 不直接访问数据库
- ❌ 不包含业务规则
**示例**
```typescript
@Controller('auth')
export class LoginController {
constructor(private readonly loginService: LoginService) {}
@Post('login')
async login(@Body() loginDto: LoginDto, @Res() res: Response): Promise<void> {
// 只做协议转换
const result = await this.loginService.login({
identifier: loginDto.identifier,
password: loginDto.password
});
// 转换为HTTP响应
this.handleResponse(result, res);
}
}
```
### 3. Business Layer业务层
**位置**`src/business/`
**职责**
- 业务逻辑实现
- 业务流程控制
- 服务协调
- 业务规则验证
- 事务管理
**原则**
- ✅ 实现所有业务逻辑
- ✅ 协调多个Core层服务
- ✅ 返回统一的业务响应
- ❌ 不处理HTTP协议
- ❌ 不直接访问数据库
**示例**
```typescript
@Injectable()
export class LoginService {
async login(loginRequest: LoginRequest): Promise<ApiResponse<LoginResponse>> {
try {
// 1. 调用核心服务进行认证
const authResult = await this.loginCoreService.login(loginRequest);
// 2. 业务逻辑验证Zulip账号
await this.validateAndUpdateZulipApiKey(authResult.user);
// 3. 生成JWT令牌
const tokenPair = await this.loginCoreService.generateTokenPair(authResult.user);
// 4. 返回业务响应
return {
success: true,
data: { user: this.formatUserInfo(authResult.user), ...tokenPair },
message: '登录成功'
};
} catch (error) {
return {
success: false,
message: error.message,
error_code: 'LOGIN_FAILED'
};
}
}
}
```
### 4. Core Layer核心层
**位置**`src/core/`
**职责**
- 数据访问(数据库、缓存)
- 基础设施Redis、消息队列
- 外部系统集成
- 技术实现细节
**原则**
- ✅ 提供技术基础设施
- ✅ 数据持久化和缓存
- ✅ 外部API集成
- ❌ 不包含业务逻辑
- ❌ 不处理HTTP协议
## 数据流向
```
客户端请求
Gateway Layer (Controller)
↓ 调用
Business Layer (Service)
↓ 调用
Core Layer (Data Access)
数据库/缓存/外部API
```
## 依赖关系
```
Gateway → Business → Core
```
- Gateway层依赖Business层
- Business层依赖Core层
- Core层不依赖任何业务层
- 依赖方向单向,不允许反向依赖
## 重构步骤
### 第一阶段:登录注册模块(已完成)
1. ✅ 创建`src/gateway/auth/`目录
2. ✅ 移动Controller到Gateway层
3. ✅ 移动DTO到Gateway层
4. ✅ 移动Guard到Gateway层
5. ✅ 创建`AuthGatewayModule`
6. ✅ 更新Business层模块移除Controller
7. ✅ 更新`app.module.ts`使用新的Gateway模块
8. ✅ 创建架构文档
### 第二阶段:其他业务模块(待进行)
- [ ] 重构`location_broadcast`模块
- [ ] 重构`user_mgmt`模块
- [ ] 重构`admin`模块
- [ ] 重构`zulip`模块
- [ ] 重构`notice`模块
### 第三阶段WebSocket模块待进行
- [ ] 创建`src/transport/websocket/`
- [ ] 实现原生WebSocket服务器
- [ ] 创建`src/gateway/location-broadcast/`
- [ ] 移动WebSocket Gateway到Gateway层
## 迁移指南
### 如何判断代码应该放在哪一层?
**Gateway层**
- 包含`@Controller()`装饰器
- 包含`@Get()`, `@Post()`等HTTP方法装饰器
- 包含`@Body()`, `@Param()`, `@Query()`等参数装饰器
- 包含DTO类`class LoginDto`
- 包含Guard类`class JwtAuthGuard`
**Business层**
- 包含`@Injectable()`装饰器
- 包含业务逻辑方法
- 协调多个服务
- 返回`ApiResponse<T>`格式的响应
**Core层**
- 包含数据库访问代码
- 包含Redis操作代码
- 包含外部API调用
- 包含技术实现细节
### 重构Checklist
对于每个模块:
1. [ ] 识别Controller文件
2. [ ] 创建对应的Gateway目录
3. [ ] 移动Controller到Gateway层
4. [ ] 移动DTO到Gateway层的`dto/`目录
5. [ ] 移动Guard到Gateway层
6. [ ] 创建Gateway Module
7. [ ] 更新Business Module移除Controller
8. [ ] 更新imports修正路径
9. [ ] 更新app.module.ts
10. [ ] 运行测试确保功能正常
## 最佳实践
### 1. 保持层级职责清晰
每一层只做自己职责范围内的事情,不要越界。
### 2. 使用统一的响应格式
Business层返回统一的`ApiResponse<T>`格式:
```typescript
interface ApiResponse<T = any> {
success: boolean;
data?: T;
message: string;
error_code?: string;
}
```
### 3. 错误处理分层
- Gateway层将业务错误转换为HTTP状态码
- Business层捕获异常并转换为业务错误
- Core层抛出技术异常
### 4. 依赖注入
使用NestJS的依赖注入系统通过Module配置依赖关系。
### 5. 文档完善
每个层级都应该有README文档说明职责和使用方法。
## 注意事项
1. **渐进式重构**:不要一次性重构所有模块,逐个模块进行
2. **保持测试**:重构后运行测试确保功能正常
3. **向后兼容**重构过程中保持API接口不变
4. **代码审查**:重构代码需要经过代码审查
5. **文档更新**:及时更新相关文档
## 参考资料
- [NestJS官方文档](https://docs.nestjs.com/)
- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)
- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/)

View File

@@ -4,28 +4,6 @@
## 核心贡献者
### 🏆 主要维护者
**moyin** - 主要维护者
- Gitea: [@moyin](https://gitea.xinghangee.icu/moyin)
- Email: xinghang_a@proton.me
- 提交数: **112 commits**
- 主要贡献:
- 🚀 项目架构设计与初始化
- 🔐 完整用户认证系统实现
- 📧 邮箱验证系统设计与开发
- 🗄️ Redis缓存服务文件存储+真实Redis双模式
- 📝 完整的API文档系统Swagger UI + OpenAPI
- 🧪 测试框架搭建与507个测试用例编写
- 📊 高性能日志系统集成Pino
- 🔧 项目配置优化与部署方案
- 🐛 验证码TTL重置关键问题修复
- 📚 完整的项目文档体系建设
- 🏗️ **Zulip模块架构重构** - 业务功能模块化架构设计与实现
- 📖 **架构文档重写** - 详细的架构设计文档和开发者指南
- 🔄 **验证码冷却时间优化** - 自动清除机制设计与实现
- 📋 **文档清理优化** - 项目文档结构化整理和维护体系建立
### 🌟 核心开发者
**angjustinl** - 核心开发者
@@ -57,13 +35,35 @@
- 📖 **技术栈文档更新** - 项目技术栈说明完善
- 🔧 **项目配置优化** - 构建和开发环境配置改进
### 🏆 主要维护者
**moyin** - 主要维护者
- Gitea: [@moyin](https://gitea.xinghangee.icu/moyin)
- Email: xinghang_a@proton.me
- 提交数: **112 commits**
- 主要贡献:
- 🚀 项目架构设计与初始化
- 🔐 完整用户认证系统实现
- 📧 邮箱验证系统设计与开发
- 🗄️ Redis缓存服务文件存储+真实Redis双模式
- 📝 完整的API文档系统Swagger UI + OpenAPI
- 🧪 测试框架搭建与507个测试用例编写
- 📊 高性能日志系统集成Pino
- 🔧 项目配置优化与部署方案
- 🐛 验证码TTL重置关键问题修复
- 📚 完整的项目文档体系建设
- 🏗️ **Zulip模块架构重构** - 业务功能模块化架构设计与实现
- 📖 **架构文档重写** - 详细的架构设计文档和开发者指南
- 🔄 **验证码冷却时间优化** - 自动清除机制设计与实现
- 📋 **文档清理优化** - 项目文档结构化整理和维护体系建立
## 贡献统计
| 贡献者 | 提交数 | 主要领域 | 贡献占比 |
|--------|--------|----------|----------|
| moyin | 112 | 架构设计、核心功能、文档、测试、Zulip重构 | 86% |
| jianuo | 11 | 管理员后台、日志系统、部署优化、配置管理 | 8% |
| angjustinl | 7 | Zulip集成、功能优化、测试、重构 | 5% |
| jianuo | 11 | 管理员后台、日志系统、部署优化、配置管理 | 8% |
| moyin | 112 | 架构设计、核心功能、文档、测试、Zulip重构 | 86% |
## 🌟 最新重要贡献
@@ -145,4 +145,4 @@
**再次感谢所有贡献者的辛勤付出!** 🙏
*如果你的名字没有出现在列表中请联系我们或提交PR更新此文件。*
*如果你的名字没有出现在列表中请联系我们或提交PR更新此文件。*

View File

@@ -1,361 +1,397 @@
# AI代码检查执行指南 - Whale Town 游戏服务器
# AI Code Inspection Guide - Whale Town Game Server
## 🎯 执行前准备
## 🎯 Pre-execution Setup
### 📋 必须收集的用户信息
在开始任何检查之前,**必须**收集以下信息:
- **用户当前日期**:用于修改记录和时间戳更新
- **用户名称**:用于@author字段处理和修改记录
### 🚀 User Information Setup
**Before starting any inspection steps, run the user information script:**
### 🏗️ 项目特性识别
本项目是**NestJS游戏服务器**,具有以下特点:
- **双模式架构**:支持数据库模式和内存模式
- **实时通信**基于WebSocket的实时双向通信
- **属性测试**管理员模块使用fast-check进行随机化测试
- **分层架构**Core层技术实现+ Business层业务逻辑
```bash
# Enter AI-reading directory
cd docs/ai-reading
## 🔄 执行原则
### 🚨 中间步骤开始规范(重要)
**如果AI从任何中间步骤开始执行非步骤1开始必须首先完成以下准备工作**
#### 📋 强制信息收集
在执行任何中间步骤之前AI必须
1. **收集用户当前日期**:用于修改记录和时间戳更新
2. **收集用户名称**:用于@author字段处理和修改记录
3. **确认项目特性**识别这是NestJS游戏服务器项目的特点
#### 🔍 全局上下文获取
AI必须先了解
- **项目架构**:双模式架构(数据库+内存、分层结构Core+Business
- **技术栈**NestJS、WebSocket、Jest测试、fast-check属性测试
- **文件结构**:当前项目的整体文件组织方式
- **已有规范**:项目中已建立的命名、注释、测试等规范
#### 🎯 执行流程约束
```
中间步骤开始请求
🚨 强制收集用户信息(日期、名称)
🚨 强制识别项目特性和上下文
🚨 强制了解目标步骤的具体要求
开始执行指定步骤
# Run user information setup script
node tools/setup-user-info.js
```
**⚠️ 违规处理如果AI跳过信息收集直接执行中间步骤用户应要求AI重新开始并完成准备工作。**
#### Script Functions
- Automatically get current date (YYYY-MM-DD format)
- Check if config file exists or date matches
- Prompt for username/nickname input if needed
- Save to `me.config.json` file for AI inspection steps
### ⚠️ 强制要求
- **分步执行**:每次只执行一个步骤,严禁跳步骤或合并执行
- **等待确认**:每步完成后必须等待用户确认才能进行下一步
- **修改验证**:每次修改文件后必须重新检查该步骤并提供验证报告
- **🔥 修改后必须重新执行当前步骤**如果在当前步骤中发生了任何修改行为文件修改、重命名、移动等AI必须立即重新执行该步骤的完整检查不能直接进入下一步骤
- **问题修复后重检**如果当前步骤出现问题需要修改时AI必须在解决问题后重新执行该步骤确保没有其他遗漏的问题
- **用户信息使用**:所有日期字段使用用户提供的真实日期,@author字段正确处理
### 🎯 执行流程
```
用户请求代码检查
收集用户信息(日期、名称)
识别项目特性
执行步骤1 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤1 → 验证报告 → 等待确认
执行步骤2 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤2 → 验证报告 → 等待确认
执行步骤3 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤3 → 验证报告 → 等待确认
执行步骤4 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤4 → 验证报告 → 等待确认
执行步骤5 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤5 → 验证报告 → 等待确认
执行步骤6 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤6 → 验证报告 → 等待确认
执行步骤7 → 提供报告 → 等待确认
[如果发生修改] → 🔥 立即重新执行步骤7 → 验证报告 → 等待确认
⚠️ 关键规则:任何步骤中发生修改行为后,必须立即重新执行该步骤!
#### Config File Format
```json
{
"date": "2026-01-13",
"name": "Developer Name"
}
```
## 📚 步骤执行指导
### 📋 Using Config in AI Inspection Steps
When AI executes inspection steps, get user info from config file:
### 步骤1命名规范检查
**执行时读取:** `step1-naming-convention.md`
**重点关注:** 文件夹结构扁平化、游戏服务器特殊文件类型
**完成后:** 提供检查报告,等待用户确认
```javascript
// Read config file
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('docs/ai-reading/me.config.json', 'utf-8'));
### 步骤2注释规范检查
**执行时读取:** `step2-comment-standard.md`
**重点关注:** @author字段处理、修改记录更新、时间戳规则
**完成后:** 提供检查报告,等待用户确认
// Get user information
const userDate = config.date; // e.g.: "2026-01-13"
const userName = config.name; // e.g.: "John"
### 步骤3代码质量检查
**执行时读取:** `step3-code-quality.md`
**重点关注:** TODO项处理、未使用代码清理
**完成后:** 提供检查报告,等待用户确认
// Use for modification records and @author fields
const modifyRecord = `- ${userDate}: Code standard optimization - Clean unused imports (Modified by: ${userName})`;
```
### 步骤4架构分层检查
**执行时读取:** `step4-architecture-layer.md`
**重点关注:** Core层命名规范、依赖关系检查
**完成后:** 提供检查报告,等待用户确认
### 🏗️ Project Characteristics
This project is a **NestJS Game Server** with the following features:
- **Dual-mode Architecture**: Supports both database and memory modes
- **Real-time Communication**: WebSocket-based real-time bidirectional communication
- **Property Testing**: Admin modules use fast-check for randomized testing
- **Layered Architecture**: Core layer (technical implementation) + Business layer (business logic)
### 步骤5测试覆盖检查
**执行时读取:** `step5-test-coverage.md`
**重点关注:** 严格一对一测试映射、测试文件位置、测试执行验证
**完成后:** 提供检查报告,等待用户确认
## 🔄 Execution Principles
#### 🧪 测试文件调试规范
**调试测试文件时必须遵循以下流程:**
### 🚨 Mid-step Start Requirements (Important)
**If AI starts execution from any intermediate step (not starting from step 1), must first complete the following preparation:**
1. **读取jest.config.js配置**
- 查看jest.config.js了解测试环境配置
- 确认testRegex模式和文件匹配规则
- 了解moduleNameMapper和其他配置项
#### 📋 Mandatory Information Collection
Before executing any intermediate step, AI must:
1. **Collect user current date**: For modification records and timestamp updates
2. **Collect user name**: For @author field handling and modification records
3. **Confirm project characteristics**: Identify NestJS game server project features
2. **使用package.json中的已有测试指令**
- **禁止自定义jest命令**必须使用package.json中scripts定义的测试命令
- **常用测试指令**
- `npm run test` - 运行所有测试
- `npm run test:unit` - 运行单元测试(.spec.ts文件)
- `npm run test:integration` - 运行集成测试(.integration.spec.ts文件)
- `npm run test:e2e` - 运行端到端测试(.e2e.spec.ts文件)
- `npm run test:watch` - 监视模式运行测试
- `npm run test:cov` - 运行测试并生成覆盖率报告
- `npm run test:debug` - 调试模式运行测试
- `npm run test:isolated` - 隔离运行测试
#### 🔍 Global Context Acquisition
AI must first understand:
- **Project Architecture**: Dual-mode architecture (database+memory), layered structure (Core+Business)
- **Tech Stack**: NestJS, WebSocket, Jest testing, fast-check property testing
- **File Structure**: Overall file organization of current project
- **Existing Standards**: Established naming, commenting, testing standards in project
#### 🎯 Execution Flow Constraints
```
Mid-step Start Request
🚨 Mandatory User Info Collection (date, name)
🚨 Mandatory Project Characteristics & Context Identification
🚨 Mandatory Understanding of Target Step Requirements
Start Executing Specified Step
```
**⚠️ Violation Handling: If AI skips information collection and directly executes intermediate steps, user should require AI to restart and complete preparation work.**
### ⚠️ Mandatory Requirements
- **Step-by-step Execution**: Execute one step at a time, strictly no step skipping or merging
- **Wait for Confirmation**: Must wait for user confirmation after each step before proceeding
- **Modification Verification**: Must re-execute current step after any file modification
- **🔥 Must Re-execute Current Step After Modification**: If any modification behavior occurs during current step (file modification, renaming, moving, etc.), AI must immediately re-execute the complete check of that step, cannot directly proceed to next step
- **Re-check After Problem Fix**: If current step has problems requiring modification, AI must re-execute the step after solving problems to ensure no other issues are missed
- **User Info Usage**: All date fields use user-provided real dates, @author fields handled correctly
### 🎯 Execution Flow
```
User Requests Code Inspection
Collect User Info (date, name)
Identify Project Characteristics
Execute Step 1 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 1 → Verification Report → Wait for Confirmation
Execute Step 2 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 2 → Verification Report → Wait for Confirmation
Execute Step 3 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 3 → Verification Report → Wait for Confirmation
Execute Step 4 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 4 → Verification Report → Wait for Confirmation
Execute Step 5 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 5 → Verification Report → Wait for Confirmation
Execute Step 6 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 6 → Verification Report → Wait for Confirmation
Execute Step 7 → Provide Report → Wait for Confirmation
[If Modification Occurs] → 🔥 Immediately Re-execute Step 7 → Verification Report → Wait for Confirmation
⚠️ Key Rule: After any modification behavior in any step, must immediately re-execute that step!
```
## 📚 Step Execution Guide
### Step 1: Naming Convention Check
**Read when executing:** `step1-naming-convention.md`
**Focus on:** Folder structure flattening, game server special file types
**After completion:** Provide inspection report, wait for user confirmation
### Step 2: Comment Standard Check
**Read when executing:** `step2-comment-standard.md`
**Focus on:** @author field handling, modification record updates, timestamp rules
**After completion:** Provide inspection report, wait for user confirmation
### Step 3: Code Quality Check
**Read when executing:** `step3-code-quality.md`
**Focus on:** TODO item handling, unused code cleanup
**After completion:** Provide inspection report, wait for user confirmation
### Step 4: Architecture Layer Check
**Read when executing:** `step4-architecture-layer.md`
**Focus on:** Core layer naming standards, dependency relationship checks
**After completion:** Provide inspection report, wait for user confirmation
### Step 5: Test Coverage Check
**Read when executing:** `step5-test-coverage.md`
**Focus on:** Strict one-to-one test mapping, test file locations, test execution verification
**After completion:** Provide inspection report, wait for user confirmation
#### 🧪 Test File Debugging Standards
**When debugging test files, must follow this workflow:**
1. **Read jest.config.js Configuration**
- Check jest.config.js to understand test environment configuration
- Confirm testRegex patterns and file matching rules
- Understand moduleNameMapper and other configuration items
2. **Use Existing Test Commands in package.json**
- **Forbidden to customize jest commands**: Must use test commands defined in package.json scripts
- **Common Test Commands**:
- `npm run test` - Run all tests
- `npm run test:unit` - Run unit tests (.spec.ts files)
- `npm run test:integration` - Run integration tests (.integration.spec.ts files)
- `npm run test:e2e` - Run end-to-end tests (.e2e.spec.ts files)
- `npm run test:watch` - Run tests in watch mode
- `npm run test:cov` - Run tests and generate coverage report
- `npm run test:debug` - Run tests in debug mode
- `npm run test:isolated` - Run tests in isolation
3. **特定模块测试指令**
- **Zulip模块测试**
- `npm run test:zulip` - 运行所有Zulip相关测试
- `npm run test:zulip:unit` - 运行Zulip单元测试
- `npm run test:zulip:integration` - 运行Zulip集成测试
- `npm run test:zulip:e2e` - 运行Zulip端到端测试
- `npm run test:zulip:performance` - 运行Zulip性能测试
3. **Specific Module Test Commands**
- **Zulip Module Tests**:
- `npm run test:zulip` - Run all Zulip-related tests
- `npm run test:zulip:unit` - Run Zulip unit tests
- `npm run test:zulip:integration` - Run Zulip integration tests
- `npm run test:zulip:e2e` - Run Zulip end-to-end tests
- `npm run test:zulip:performance` - Run Zulip performance tests
4. **测试执行验证流程**
4. **Test Execution Verification Workflow**
```
发现测试问题 → 读取jest.config.js → 选择合适的npm run test:xxx指令 → 执行测试 → 分析结果 → 修复问题 → 重新执行测试
Discover Test Issue → Read jest.config.js → Choose Appropriate npm run test:xxx Command → Execute Test → Analyze Results → Fix Issues → Re-execute Test
```
5. **测试指令选择原则**
- **单个文件测试**:使用`npm run test -- 文件路径`
- **特定类型测试**使用对应的test:xxx指令
- **调试测试**:优先使用`npm run test:debug`
- **CI/CD环境**:使用`npm run test:isolated`
5. **Test Command Selection Principles**
- **Single File Test**: Use `npm run test -- file_path`
- **Specific Type Test**: Use corresponding test:xxx command
- **Debug Test**: Prioritize `npm run test:debug`
- **CI/CD Environment**: Use `npm run test:isolated`
### 步骤6功能文档生成
**执行时读取:** `step6-documentation.md`
**重点关注:** API接口文档、WebSocket事件文档
**完成后:** 提供检查报告,等待用户确认
### Step 6: Function Documentation Generation
**Read when executing:** `step6-documentation.md`
**Focus on:** API interface documentation, WebSocket event documentation
**After completion:** Provide inspection report, wait for user confirmation
### 步骤7代码提交
**执行时读取:** `step7-code-commit.md`
**重点关注:** Git变更校验、修改记录一致性检查、规范化提交流程
**完成后:** 提供检查报告,等待用户确认
### Step 7: Code Commit
**Read when executing:** `step7-code-commit.md`
**Focus on:** Git change verification, modification record consistency check, standardized commit process
**After completion:** Provide inspection report, wait for user confirmation
## 📋 统一报告模板
## 📋 Unified Report Template
每步完成后使用此模板报告:
Use this template for reporting after each step completion:
```
## 步骤X[步骤名称]检查报告
## Step X: [Step Name] Inspection Report
### 🔍 检查结果
[发现的问题列表]
### 🔍 Inspection Results
[List of discovered issues]
### 🛠️ 修正方案
[具体修正建议]
### 🛠️ Correction Plan
[Specific correction suggestions]
### ✅ 完成状态
- 检查项1 ✓/✗
- 检查项2 ✓/✗
### ✅ Completion Status
- Check Item 1 ✓/✗
- Check Item 2 ✓/✗
**请确认修正方案,确认后进行下一步骤**
**Please confirm correction plan, proceed to next step after confirmation**
```
## 🚨 全局约束
## 🚨 Global Constraints
### 📝 文件修改记录规范(重要)
**每次执行完修改后,文件顶部都需要更新修改记录和相关信息**
### 📝 File Modification Record Standards (Important)
**After each modification execution, file headers need to update modification records and related information**
#### 修改类型定义
- `代码规范优化` - 命名规范、注释规范、代码清理等
- `功能新增` - 添加新的功能或方法
- `功能修改` - 修改现有功能的实现
- `Bug修复` - 修复代码缺陷
- `性能优化` - 提升代码性能
- `重构` - 代码结构调整但功能不变
#### Modification Type Definitions
- `Code Standard Optimization` - Naming standards, comment standards, code cleanup, etc.
- `Feature Addition` - Adding new features or methods
- `Feature Modification` - Modifying existing feature implementations
- `Bug Fix` - Fixing code defects
- `Performance Optimization` - Improving code performance
- `Refactoring` - Code structure adjustment but functionality unchanged
#### 修改记录格式要求
#### Modification Record Format Requirements
```typescript
/**
* 最近修改:
* - [用户日期]: 代码规范优化 - 清理未使用的导入 (修改者: [用户名称])
* - 2024-01-06: Bug修复 - 修复邮箱验证逻辑错误 (修改者: 李四)
* - 2024-01-05: 功能新增 - 添加用户验证码登录功能 (修改者: 王五)
* Recent Modifications:
* - [User Date]: Code Standard Optimization - Clean unused imports (Modified by: [User Name])
* - 2024-01-06: Bug Fix - Fix email validation logic error (Modified by: Li Si)
* - 2024-01-05: Feature Addition - Add user verification code login feature (Modified by: Wang Wu)
*
* @author [处理后的作者名称]
* @author [Processed Author Name]
* @version x.x.x
* @since [创建日期]
* @lastModified [用户日期]
* @since [Creation Date]
* @lastModified [User Date]
*/
```
#### 🔢 最近修改记录数量限制
- **最多保留5条**最近修改记录最多只保留最新的5条记录
- **超出自动删除**当添加新的修改记录时如果超过5条自动删除最旧的记录
- **保持时间顺序**:记录按时间倒序排列,最新的在最上面
- **完整记录保留**:每条记录必须包含完整的日期、修改类型、描述和修改者信息
#### 🔢 Recent Modification Record Quantity Limit
- **Maximum 5 Records**: Recent modification records keep maximum of 5 latest records
- **Auto-delete When Exceeded**: When adding new modification records, if exceeding 5, automatically delete oldest records
- **Maintain Time Order**: Records arranged in reverse chronological order, newest at top
- **Complete Record Retention**: Each record must include complete date, modification type, description and modifier information
#### 版本号递增规则
- **修订版本+1**代码规范优化、Bug修复 (1.0.0 → 1.0.1)
- **次版本+1**:功能新增、功能修改 (1.0.1 → 1.1.0)
- **主版本+1**:重构、架构变更 (1.1.0 → 2.0.0)
#### Version Number Increment Rules
- **Patch Version +1**: Code standard optimization, bug fixes (1.0.0 → 1.0.1)
- **Minor Version +1**: Feature addition, feature modification (1.0.1 → 1.1.0)
- **Major Version +1**: Refactoring, architecture changes (1.1.0 → 2.0.0)
#### 时间更新规则
- **仅检查不修改**:如果只是检查而没有实际修改文件内容,**不更新**@lastModified字段
- **实际修改才更新**:只有真正修改了文件内容时才更新@lastModified字段和添加修改记录
- **Git变更检测**:通过`git status``git diff`检查文件是否有实际变更只有git显示文件被修改时才需要添加修改记录和更新时间戳
#### Time Update Rules
- **Check Only No Modification**: If only checking without actually modifying file content, **do not update** @lastModified field
- **Update Only on Actual Modification**: Only update @lastModified field and add modification records when actually modifying file content
- **Git Change Detection**: Check if files have actual changes through `git status` and `git diff`, only add modification records and update timestamps when git shows files are modified
#### 🚨 重要强调:纯检查步骤不更新修改记录
**AI在执行代码检查步骤时如果发现代码已经符合规范无需任何修改**
- **禁止添加修改记录**:不要添加类似"AI代码检查步骤XXXX检查和优化"的记录
- **禁止更新时间戳**:不要更新@lastModified字段
- **禁止递增版本号**:不要修改@version字段
- **只有实际修改了代码内容、注释内容、结构等才需要更新修改记录**
#### 🚨 Important Emphasis: Pure Check Steps Do Not Update Modification Records
**When AI executes code inspection steps, if code already meets standards and needs no modification, then:**
- **Forbidden to Add Modification Records**: Do not add records like "AI code inspection step X: XXX check and optimization"
- **Forbidden to Update Timestamps**: Do not update @lastModified field
- **Forbidden to Increment Version Numbers**: Do not modify @version field
- **Only add modification records when actually modifying code content, comment content, structure, etc.**
**错误示例**
**Wrong Example**:
```typescript
// ❌ 错误:仅检查无修改却添加了修改记录
// ❌ Wrong: Only checked without modification but added modification record
/**
* 最近修改:
* - 2026-01-12: 代码规范优化 - AI代码检查步骤2注释规范检查和优化 (修改者: moyin) // 这是错误的!
* - 2026-01-07: 功能新增 - 添加用户验证功能 (修改者: 张三)
* Recent Modifications:
* - 2026-01-12: Code Standard Optimization - AI code inspection step 2: Comment standard check and optimization (Modified by: moyin) // This is wrong!
* - 2026-01-07: Feature Addition - Add user verification feature (Modified by: Zhang San)
*/
```
**正确示例**
**Correct Example**:
```typescript
// ✅ 正确:检查发现符合规范,不添加修改记录
// ✅ Correct: Check found compliance with standards, do not add modification records
/**
* 最近修改:
* - 2026-01-07: 功能新增 - 添加用户验证功能 (修改者: 张三) // 保持原有记录不变
* Recent Modifications:
* - 2026-01-07: Feature Addition - Add user verification feature (Modified by: Zhang San) // Keep original records unchanged
*/
```
### @author字段处理规范
- **保留原则**:人名必须保留,不得随意修改
- **AI标识替换**只有AI标识kiroChatGPTClaude、AI等才可替换为用户名称
- **判断示例**`@author kiro` → 可替换,`@author 张三` → 必须保留
### @author Field Handling Standards
- **Retention Principle**: Human names must be retained, cannot be arbitrarily modified
- **AI Identifier Replacement**: Only AI identifiers (kiro, ChatGPT, Claude, AI, etc.) can be replaced with user names
- **Judgment Example**: `@author kiro` → Can replace, `@author Zhang San` → Must retain
### 游戏服务器特殊要求
- **WebSocket文件**Gateway文件必须有完整的连接、消息处理测试
- **双模式服务**:内存服务和数据库服务都需要完整测试覆盖
- **属性测试**管理员模块使用fast-check进行属性测试
- **测试分离**严格区分单元测试、集成测试、E2E测试、性能测试
### Game Server Special Requirements
- **WebSocket Files**: Gateway files must have complete connection and message processing tests
- **Dual-mode Services**: Both memory services and database services need complete test coverage
- **Property Testing**: Admin modules use fast-check for property testing
- **Test Separation**: Strictly distinguish unit tests, integration tests, E2E tests, performance tests
## 🔧 修改验证流程
## 🔧 Modification Verification Process
### 🔥 修改后立即重新执行规则(重要)
**任何步骤中发生修改行为后AI必须立即重新执行该步骤不能直接进入下一步骤**
### 🔥 Immediately Re-execute Rule After Modification (Important)
**After any modification behavior occurs in any step, AI must immediately re-execute that step, cannot directly proceed to next step!**
#### 修改行为包括但不限于:
- 文件内容修改(代码、注释、配置等)
- 文件重命名
- 文件移动
- 文件删除
- 新建文件
- 文件夹结构调整
#### Modification Behaviors Include But Not Limited To:
- File content modification (code, comments, configuration, etc.)
- File renaming
- File moving
- File deletion
- New file creation
- Folder structure adjustment
#### 强制执行流程:
#### Mandatory Execution Process:
```
步骤执行中 → 发现问题 → 执行修改 → 🔥 立即重新执行该步骤 → 验证无遗漏 → 用户确认 → 下一步骤
Step Execution → Discover Issues → Execute Modifications → 🔥 Immediately Re-execute That Step → Verify No Omissions → User Confirmation → Next Step
```
### 问题修复后的重检流程
当在任何步骤中发现问题并进行修改后,必须遵循以下流程:
### Re-check Process After Problem Fix
When issues are discovered and modifications made in any step, must follow this process:
1. **执行修改操作**
- 根据发现的问题进行具体修改
- 确保修改内容准确无误
- **更新文件顶部的修改记录、版本号和@lastModified字段**
1. **Execute Modification Operations**
- Make specific modifications based on discovered issues
- Ensure modification content is accurate
- **Update file header modification records, version numbers and @lastModified fields**
2. **🔥 立即重新执行当前步骤**
- **不能跳过这一步!**
- 完整重新执行该步骤的所有检查项
- 不能只检查修改的部分,必须全面重检
2. **🔥 Immediately Re-execute Current Step**
- **Cannot skip this step!**
- Complete re-execution of all check items for that step
- Cannot only check modified parts, must comprehensively re-check
3. **提供验证报告**
- 确认之前发现的问题已解决
- 确认没有引入新的问题
- 确认没有遗漏其他问题
3. **Provide Verification Report**
- Confirm previously discovered issues are resolved
- Confirm no new issues introduced
- Confirm no other issues omitted
4. **等待用户确认**
- 提供完整的验证报告
- 等待用户确认后才能进行下一步骤
4. **Wait for User Confirmation**
- Provide complete verification report
- Wait for user confirmation before proceeding to next step
### 验证报告模板
### Verification Report Template
```
## 步骤X修改验证报告
## Step X: Modification Verification Report
### 🔧 已执行的修改操作
- 修改类型:[文件修改/重命名/移动/删除等]
- 修改内容:[具体修改描述]
- 影响文件:[受影响的文件列表]
### 🔧 Executed Modification Operations
- Modification Type: [File modification/renaming/moving/deletion, etc.]
- Modification Content: [Specific modification description]
- Affected Files: [List of affected files]
### 📝 已更新的修改记录
- 添加修改记录:[用户日期]: [修改类型] - [修改内容] (修改者: [用户名称])
- 更新版本号:[旧版本] → [新版本]
- 更新时间戳:@lastModified [用户日期]
### 📝 Updated Modification Records
- Added Modification Record: [User Date]: [Modification Type] - [Modification Content] (Modified by: [User Name])
- Updated Version Number: [Old Version] → [New Version]
- Updated Timestamp: @lastModified [User Date]
### 🔍 重新执行步骤X的完整检查结果
[完整重新执行该步骤的所有检查项的结果]
### 🔍 Re-executed Step X Complete Check Results
[Complete re-execution results of all check items for that step]
### ✅ 验证状态
- 原问题已解决
- 修改记录已更新
- 无新问题引入
- 无其他遗漏问题
- 步骤X检查完全通过
### ✅ Verification Status
- Original Issues Resolved
- Modification Records Updated
- No New Issues Introduced
- No Other Issues Omitted
- Step X Check Completely Passed
**🔥 重要:本步骤已完成修改并重新验证,请确认后进行下一步骤**
**🔥 Important: This step has completed modification and re-verification, please confirm before proceeding to next step**
```
### 重检的重要性
- **确保完整性**:避免修改过程中遗漏其他问题
- **防止新问题**:确保修改没有引入新的问题
- **保证质量**:每个步骤都达到完整的检查标准
- **维护一致性**:确保整个检查过程的严谨性
- **🔥 强制执行**:修改后必须重新执行,不能跳过这个环节
### Importance of Re-checking
- **Ensure Completeness**: Avoid omitting other issues during modification process
- **Prevent New Issues**: Ensure modifications do not introduce new problems
- **Maintain Quality**: Each step reaches complete inspection standards
- **Maintain Consistency**: Ensure rigor throughout entire inspection process
- **🔥 Mandatory Execution**: Cannot skip this step after modifications
## ⚡ 关键成功要素
## ⚡ Key Success Factors
- **严格按步骤执行**:不跳步骤,不合并执行
- **🔥 修改后立即重新执行**:任何修改行为后必须立即重新执行当前步骤,不能直接进入下一步
- **问题修复后必须重检**:修改文件后必须重新执行整个步骤,确保无遗漏
- **修改记录必须更新**:每次修改文件后都必须更新文件顶部的修改记录、版本号和时间戳
- **真实修改验证**:通过工具验证修改效果
- **用户信息准确使用**:日期和名称信息正确应用
- **项目特性适配**:针对游戏服务器特点优化检查
- **完整报告提供**:每步都提供详细的检查报告
- **Strict Step-by-step Execution**: No step skipping, no merged execution
- **🔥 Immediately Re-execute After Modification**: Must immediately re-execute current step after any modification behavior, cannot directly proceed to next step
- **Must Re-check After Problem Fix**: Must re-execute entire step after file modification to ensure no omissions
- **Must Update Modification Records**: Must update file header modification records, version numbers and timestamps after each file modification
- **Real Modification Verification**: Verify modification effects through tools
- **Accurate User Info Usage**: Correctly apply date and name information
- **Project Characteristic Adaptation**: Optimize inspections for game server characteristics
- **Complete Report Provision**: Provide detailed inspection reports for each step
---
**开始执行前,请确认已收集用户日期和名称信息!**
**Before starting execution, please first run `node tools/setup-user-info.js` to set user information!**

View File

@@ -22,11 +22,63 @@
## 📋 命名规范标准
### 文件和文件夹命名
#### 🚨 NestJS 框架文件命名规范(重要)
**本项目使用 NestJS 框架,框架相关文件命名规则:**
**命名组成 = 文件名snake_case + 类型标识符(点分隔) + 扩展名**
```
✅ 正确的 NestJS 文件命名:
- login.controller.ts # 单词文件名 + .controller
- user_profile.service.ts # snake_case文件名 + .service
- auth_core.module.ts # snake_case文件名 + .module
- login_request.dto.ts # snake_case文件名 + .dto
- jwt_auth.guard.ts # snake_case文件名 + .guard
- current_user.decorator.ts # snake_case文件名 + .decorator
- user_profile.controller.spec.ts # snake_case文件名 + .controller.spec
❌ 错误的命名示例:
- loginController.ts # 错误!应该是 login.controller.ts
- user-profile.service.ts # 错误!应该是 user_profile.service.ts
- authCore.module.ts # 错误!应该是 auth_core.module.ts
- login_controller.ts # 错误!类型标识符应该用点分隔,不是下划线
```
**关键规则:**
1. **文件名部分**:使用 snake_case`user_profile``auth_core`
2. **类型标识符**:使用点分隔(如 `.controller``.service`
3. **完整格式**`文件名.类型标识符.ts`(如 `user_profile.service.ts`
**NestJS 文件类型标识符(必须使用点分隔):**
- `.controller.ts` - 控制器(如 `user_auth.controller.ts`
- `.service.ts` - 服务(如 `user_profile.service.ts`
- `.module.ts` - 模块(如 `auth_core.module.ts`
- `.dto.ts` - 数据传输对象(如 `login_request.dto.ts`
- `.entity.ts` - 实体(如 `user_account.entity.ts`
- `.interface.ts` - 接口(如 `game_config.interface.ts`
- `.guard.ts` - 守卫(如 `jwt_auth.guard.ts`
- `.interceptor.ts` - 拦截器(如 `response_transform.interceptor.ts`
- `.pipe.ts` - 管道(如 `validation_pipe.pipe.ts`
- `.filter.ts` - 过滤器(如 `http_exception.filter.ts`
- `.decorator.ts` - 装饰器(如 `current_user.decorator.ts`
- `.middleware.ts` - 中间件(如 `logger_middleware.middleware.ts`
- `.spec.ts` - 单元测试(如 `user_profile.service.spec.ts`
- `.e2e.spec.ts` - E2E 测试(如 `auth_flow.e2e.spec.ts`
**命名规则说明:**
1. **文件名使用 snake_case**:多个单词用下划线连接(如 `user_profile``auth_core`
2. **类型标识符使用点分隔**:遵循 NestJS/Angular 风格(如 `.controller``.service`
3. **组合格式**`snake_case文件名.类型标识符.ts`
4. **社区标准**:这是本项目结合 NestJS 规范和 snake_case 约定的标准做法
#### 普通文件和文件夹命名
- **规则**snake_case下划线分隔保持项目一致性
- **适用范围**:非 NestJS 框架文件、工具类、配置文件、普通文件夹等
- **示例**
```
✅ 正确user_controller.ts, admin_operation_log_service.ts
❌ 错误UserController.ts, user-service.ts, adminOperationLog.service.ts
✅ 正确user_utils.ts, admin_operation_log.ts, config_loader.ts
❌ 错误UserUtils.ts, user-utils.ts, adminOperationLog.ts
```
### 变量和函数命名
@@ -161,6 +213,14 @@ src/business/auth/
2. **凭印象判断,不使用工具获取准确数据**
3. **遗漏≤3个文件文件夹的识别**
4. **忽略测试文件夹扁平化**认为tests文件夹是"标准结构"
5. **🚨 错误地要求修改 NestJS 框架文件命名**
- ❌ 错误:要求将 `login.controller.ts` 改为 `login_controller.ts`(类型标识符不能用下划线)
- ❌ 错误:要求将 `userProfile.service.ts` 改为 `userProfile.service.ts`(文件名应该用 snake_case
- ✅ 正确:`user_profile.service.ts`(文件名用 snake_case + 类型标识符用点分隔)
- **判断方法**
- 检查类型标识符是否用点分隔(`.controller`、`.service` 等)
- 检查文件名本身是否用 snake_case
- 完整格式:`snake_case文件名.类型标识符.ts`
## 🔍 检查执行步骤

View File

@@ -24,21 +24,142 @@
### 项目分层结构
```
src/
├── core/ # Core层技术实现层
│ ├── db/ # 数据访问
│ ├── redis/ # 缓存服务
│ └── utils/ # 工具服务
├── gateway/ # Gateway层网关层HTTP协议处理
│ ├── auth/ # 认证网关
│ ├── users/ # 用户网关
│ └── admin/ # 管理网关
├── business/ # Business层业务逻辑层
│ ├── auth/ # 认证业务
│ ├── users/ # 用户业务
│ └── admin/ # 管理业务
├── core/ # Core层技术实现层
│ ├── db/ # 数据访问
│ ├── redis/ # 缓存服务
│ └── utils/ # 工具服务
└── common/ # 公共层:通用组件
```
### 4层架构说明
**Gateway Layer网关层**
- 位置:`src/gateway/`
- 职责HTTP协议处理、数据验证、路由管理、认证守卫、错误转换
- 依赖Business层
**Business Layer业务层**
- 位置:`src/business/`
- 职责:业务逻辑实现、业务流程控制、服务协调、业务规则验证
- 依赖Core层
**Core Layer核心层**
- 位置:`src/core/`
- 职责:数据访问、基础设施、外部系统集成、技术实现细节
- 依赖:无(或第三方库)
### 检查范围
- **限制范围**:仅检查当前执行检查的文件夹
- **不跨模块**:不考虑其他同层功能模块
- **专注职责**:确保当前模块职责清晰
- **按层检查**:根据文件夹所在层级应用对应的检查规则
## 🌐 Gateway层规范检查
### 职责定义
**Gateway层专注HTTP协议处理不包含业务逻辑**
### Gateway层协议处理示例
```typescript
// ✅ 正确Gateway层只做协议转换
@Controller('auth')
export class LoginController {
constructor(private readonly loginService: LoginService) {}
@Post('login')
async login(@Body() loginDto: LoginDto, @Res() res: Response): Promise<void> {
// 1. 接收HTTP请求使用DTO验证
// 2. 调用Business层服务
const result = await this.loginService.login({
identifier: loginDto.identifier,
password: loginDto.password
});
// 3. 将业务响应转换为HTTP响应
this.handleResponse(result, res);
}
private handleResponse(result: any, res: Response): void {
if (result.success) {
res.status(HttpStatus.OK).json(result);
} else {
const statusCode = this.getErrorStatusCode(result);
res.status(statusCode).json(result);
}
}
}
// ❌ 错误Gateway层包含业务逻辑
@Controller('auth')
export class LoginController {
@Post('login')
async login(@Body() loginDto: LoginDto): Promise<any> {
// 错误在Controller中实现业务逻辑
const user = await this.userRepository.findOne({
where: { username: loginDto.identifier }
});
if (!user) {
throw new NotFoundException('用户不存在');
}
const isValid = await bcrypt.compare(loginDto.password, user.password);
if (!isValid) {
throw new UnauthorizedException('密码错误');
}
// ... 更多业务逻辑
}
}
```
### Gateway层依赖关系检查
```typescript
// ✅ 允许的导入
import { Controller, Post, Body, Res } from '@nestjs/common'; # NestJS框架
import { Response } from 'express'; # Express类型
import { LoginService } from '../../business/auth/login.service'; # Business层服务
import { LoginDto } from './dto/login.dto'; # DTO
import { JwtAuthGuard } from './jwt_auth.guard'; # Guard
// ❌ 禁止的导入
import { LoginCoreService } from '../../core/login_core/login_core.service'; # Business层直接调用Core层
import { UsersRepository } from '../../core/db/users/users.repository'; # 访
import { RedisService } from '../../core/redis/redis.service'; # 访
```
### Gateway层文件类型检查
```typescript
// ✅ Gateway层应该包含的文件类型
- *.controller.ts # HTTP控制器
- *.dto.ts #
- *.guard.ts # /
- *.decorator.ts #
- *.interceptor.ts #
- *.filter.ts #
- *.gateway.module.ts #
// ❌ Gateway层不应该包含的文件类型
- *.service.ts # Business层
- *.repository.ts # Core层
- *.entity.ts # Core层
```
### Gateway层职责检查清单
- [ ] Controller方法是否只做协议转换
- [ ] 是否使用DTO进行数据验证
- [ ] 是否调用Business层服务而非Core层
- [ ] 是否有统一的错误处理机制?
- [ ] 是否包含Swagger API文档
- [ ] 是否使用限流和超时保护?
## 🔧 Core层规范检查
@@ -202,6 +323,42 @@ import { DatabaseConnection } from '../../core/db/connection';
## 🚨 常见架构违规
### Gateway层违规示例
```typescript
// ❌ 错误Gateway层包含业务逻辑
@Controller('users')
export class UserController {
@Post('register')
async register(@Body() registerDto: RegisterDto): Promise<User> {
// 违规在Controller中实现业务验证
if (registerDto.age < 18) {
throw new BadRequestException('用户年龄必须大于18岁');
}
// 违规在Controller中协调多个服务
const user = await this.userCoreService.create(registerDto);
await this.emailService.sendWelcomeEmail(user.email);
await this.zulipService.createAccount(user);
return user;
}
}
// ❌ 错误Gateway层直接调用Core层
@Controller('auth')
export class LoginController {
constructor(
private readonly loginCoreService: LoginCoreService, // 违规跳过Business层
) {}
@Post('login')
async login(@Body() loginDto: LoginDto): Promise<any> {
// 违规直接调用Core层服务
return this.loginCoreService.login(loginDto);
}
}
```
### Business层违规示例
```typescript
// ❌ 错误Business层包含技术实现细节
@@ -288,30 +445,49 @@ export class UsersBusinessService {
## 🔍 检查执行步骤
1. **识别当前模块的层级**
- 确定是Core层还是Business层
- 确定是Gateway层、Business层还是Core层
- 检查文件夹路径和命名
- 根据层级应用对应的检查规则
2. **检查Core层命名规范**
2. **Gateway层检查如果是Gateway层**
- 检查是否只包含协议处理代码
- 检查是否使用DTO进行数据验证
- 检查是否只调用Business层服务
- 检查是否有统一的错误处理
- 检查文件类型是否符合Gateway层规范
3. **Business层检查如果是Business层**
- 检查是否只包含业务逻辑
- 检查是否协调多个Core层服务
- 检查是否返回统一的业务响应
- 检查是否不包含HTTP协议处理
4. **Core层检查如果是Core层**
- 检查Core层命名规范
- 业务支撑模块是否使用_core后缀
- 通用工具模块是否不使用后缀
- 根据模块职责判断命名正确性
- 检查是否只包含技术实现
3. **检查职责分离**
- Core层是否只包含技术实现
5. **检查职责分离**
- Gateway层是否只做协议转换
- Business层是否只包含业务逻辑
- Core层是否只包含技术实现
- 是否有跨层职责混乱
4. **检查依赖关系**
- Core层是否导入了Business层模块
- Business层是否直接使用底层技术实现
6. **检查依赖关系**
- Gateway层是否只依赖Business层
- Business层是否只依赖Core层
- Core层是否不依赖业务层
- 依赖注入是否正确使用
5. **检查架构违规**
7. **检查架构违规**
- 识别常见的分层违规模式
- 检查技术实现和业务逻辑的边界
- 检查协议处理和业务逻辑的边界
- 确保架构清晰度
6. **游戏服务器特殊检查**
8. **游戏服务器特殊检查**
- WebSocket Gateway的分层正确性
- 双模式服务的架构设计
- 实时通信组件的职责分离

View File

@@ -0,0 +1,115 @@
#!/usr/bin/env node
/**
* AI代码检查用户信息管理脚本
*
* 功能获取当前日期和用户名称保存到me.config.json供AI检查步骤使用
*
* @author AI助手
* @version 1.0.0
* @since 2026-01-13
*/
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const configPath = path.join(__dirname, '..', 'me.config.json');
// 获取当前日期YYYY-MM-DD格式
function getCurrentDate() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// 读取现有配置
function readConfig() {
try {
if (!fs.existsSync(configPath)) {
return null;
}
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
} catch (error) {
console.error('❌ 读取配置文件失败:', error);
return null;
}
}
// 保存配置
function saveConfig(config) {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
console.log('✅ 配置已保存');
} catch (error) {
console.error('❌ 保存配置失败:', error);
throw error;
}
}
// 提示用户输入名称
function promptUserName() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
rl.question('👤 请输入您的名称或昵称: ', (name) => {
rl.close();
resolve(name.trim());
});
});
}
// 主执行逻辑
async function main() {
console.log('🚀 AI代码检查 - 用户信息设置');
const currentDate = getCurrentDate();
console.log('📅 当前日期:', currentDate);
const existingConfig = readConfig();
// 如果配置存在且日期匹配,直接返回
if (existingConfig && existingConfig.date === currentDate) {
console.log('✅ 配置已是最新,当前用户:', existingConfig.name);
return existingConfig;
}
// 需要更新配置
console.log('🔄 需要更新用户信息...');
const userName = await promptUserName();
if (!userName) {
console.error('❌ 用户名称不能为空');
process.exit(1);
}
const config = {
date: currentDate,
name: userName
};
saveConfig(config);
console.log('🎉 设置完成!', config);
return config;
}
// 导出函数供其他脚本使用
function getConfig() {
return readConfig();
}
// 如果直接运行此脚本
if (require.main === module) {
main().catch((error) => {
console.error('❌ 脚本执行失败:', error);
process.exit(1);
});
}
module.exports = { getConfig, getCurrentDate };