diff --git a/.cursor/rules/01-project-structure.mdc b/.cursor/rules/01-project-structure.mdc new file mode 100644 index 0000000..c1efef5 --- /dev/null +++ b/.cursor/rules/01-project-structure.mdc @@ -0,0 +1,34 @@ +--- +description: +globs: +alwaysApply: false +--- +# Project Structure + +## Main Entry Points + +The application entry point is [src/index.ts](mdc:src/index.ts), which sets up the Hono web server and defines the main routes. + +## Core Directories + +- **src/**: Contains all source code + - **controllers/**: Route handlers and business logic + - **services/**: Service layer for external API interactions + - **config/**: Configuration management + - **utils/**: Utility functions + +## Configuration Files + +- [package.json](mdc:package.json): Project dependencies and scripts +- [tsconfig.json](mdc:tsconfig.json): TypeScript compiler configuration +- [Dockerfile](mdc:Dockerfile): Container configuration +- [kubernetes.yaml](mdc:kubernetes.yaml): Kubernetes deployment configuration + +## Build and Deployment + +The project uses Bun for development and production: +- `bun run dev`: Development mode with watch +- `bun run build`: Build production assets +- `bun run start`: Run in production + +Docker and Kubernetes configurations are available for containerized deployment. diff --git a/.cursor/rules/02-architecture-and-features.mdc b/.cursor/rules/02-architecture-and-features.mdc new file mode 100644 index 0000000..78561e3 --- /dev/null +++ b/.cursor/rules/02-architecture-and-features.mdc @@ -0,0 +1,71 @@ +--- +description: +globs: +alwaysApply: false +--- +# Architecture and Features + +## Core Features + +This application is a Gitea Assistant that provides AI-driven code review capabilities for Gitea repositories. Key features include: + +- AI code review for Pull Requests +- AI code review for successful commit statuses +- Integration with OpenAI API for code analysis +- Both summary and line-level code comments +- Secure webhook validation +- PR notification system via Feishu + +## Architecture + +The application follows a clean, layered architecture: + +1. **Controller Layer** ([src/controllers/review.ts](mdc:src/controllers/review.ts)) + - Handles webhook requests from Gitea + - Processes different event types (PR events, status events) + - Manages PR notification triggers + +2. **Service Layer** + - [src/services/gitea.ts](mdc:src/services/gitea.ts): Interacts with Gitea API + - [src/services/ai-review.ts](mdc:src/services/ai-review.ts): Manages AI code review logic + - [src/services/feishu.ts](mdc:src/services/feishu.ts): Handles Feishu notifications + - PR creation notifications + - Reviewer assignment notifications + - Error handling and retry mechanisms + +3. **Configuration Layer** ([src/config/index.ts](mdc:src/config/index.ts)) + - Centralizes application configuration from environment variables + - Manages Feishu webhook configurations + +4. **Utilities** + - [src/utils/logger.ts](mdc:src/utils/logger.ts): Custom logging utilities + +## Webhook Flow + +1. Gitea sends webhook events to `/webhook/gitea` +2. Signature verification ensures request authenticity +3. Events are processed based on their type: + - Pull Request events: + - Trigger code review on the PR + - Send notifications to reviewers (if applicable) + - Status events trigger code review on successful commits + +## Notification Flow + +1. **PR Creation Flow** + - PR webhook event received + - Event validated and processed + - If reviewers are assigned: + - Feishu notification prepared with PR details + - Notification sent to all assigned reviewers + +2. **Reviewer Assignment Flow** + - PR review_requested event received + - New reviewer information extracted + - Feishu notification sent to newly assigned reviewer + - Notification includes PR title and direct link + +3. **Error Handling** + - Failed notifications are logged but don't block the review process + - Automatic retry mechanism for failed notifications + - Errors are captured and logged for monitoring diff --git a/.cursor/rules/03-tech-stack-and-dependencies.mdc b/.cursor/rules/03-tech-stack-and-dependencies.mdc new file mode 100644 index 0000000..d8f88c8 --- /dev/null +++ b/.cursor/rules/03-tech-stack-and-dependencies.mdc @@ -0,0 +1,45 @@ +--- +description: +globs: +alwaysApply: true +--- +# Technology Stack and Dependencies + +## Core Technologies + +- **Runtime**: Bun (JavaScript/TypeScript runtime) +- **Language**: TypeScript +- **Framework**: Hono (lightweight web framework) +- **API Integration**: OpenAI API, Gitea API +- **Containerization**: Docker, Kubernetes + +## Key Dependencies + +From [package.json](mdc:package.json): + +### Production Dependencies + +- **hono**: Lightweight, ultrafast web framework +- **@hono/zod-validator**: Schema validation for Hono +- **zod**: TypeScript-first schema validation +- **openai**: OpenAI API client +- **axios**: HTTP client for API requests +- **dotenv**: Environment variable management +- **lodash-es**: Utility library + +### Development Dependencies + +- **typescript**: TypeScript compiler and type definitions +- **tslint**: Code linting +- **@types/node**: Node.js type definitions +- **@types/lodash-es**: Type definitions for lodash-es + +## Environment Configuration + +The application uses environment variables for configuration, which are processed in [src/config/index.ts](mdc:src/config/index.ts). Key configurations include: + +- Gitea API settings +- OpenAI API settings +- Custom prompts for AI review +- Server configuration +- Webhook security diff --git a/.cursor/rules/04-ai-code-review.mdc b/.cursor/rules/04-ai-code-review.mdc new file mode 100644 index 0000000..2b5b9e0 --- /dev/null +++ b/.cursor/rules/04-ai-code-review.mdc @@ -0,0 +1,54 @@ +--- +description: +globs: +alwaysApply: true +--- +# AI Code Review System + +## Overview + +The AI Code Review system is the core feature of this application. It automatically analyzes code changes in Pull Requests and commits, providing insightful feedback using OpenAI's language models. + +## Key Components + +- **Review Controller**: [src/controllers/review.ts](mdc:src/controllers/review.ts) + - Handles webhook events from Gitea + - Routes events to appropriate handlers + +- **AI Review Service**: [src/services/ai-review.ts](mdc:src/services/ai-review.ts) + - Contains the core logic for AI-powered code review + - Generates both summary comments and line-level feedback + - Customizable prompts for different review contexts + +- **Gitea Service**: [src/services/gitea.ts](mdc:src/services/gitea.ts) + - Fetches code diffs and file contents from Gitea API + - Posts review comments back to Gitea + +## Review Workflow + +1. **Trigger**: + - Pull Request created/updated or + - Commit status changes to "success" + +2. **Code Analysis**: + - Fetch diff content from Gitea + - Process and analyze changes + - Generate AI prompts with context + +3. **AI Review**: + - Send processed data to OpenAI API + - Generate summary feedback + - Generate line-level comments + +4. **Feedback Delivery**: + - Post summary comment to PR or commit + - Add line comments to specific code sections + - Apply formatting for better readability + +## Customization + +The system supports customizable prompts through environment variables: +- `CUSTOM_SUMMARY_PROMPT`: For overall review summaries +- `CUSTOM_LINE_COMMENT_PROMPT`: For line-specific comments + +Default prompts are designed to focus on bugs and serious issues rather than style or minor concerns. diff --git a/.cursor/rules/05-deployment-and-configuration.mdc b/.cursor/rules/05-deployment-and-configuration.mdc new file mode 100644 index 0000000..fe72f47 --- /dev/null +++ b/.cursor/rules/05-deployment-and-configuration.mdc @@ -0,0 +1,69 @@ +--- +description: +globs: +alwaysApply: false +--- +# Deployment and Configuration + +## Environment Variables + +The application is configured through environment variables, defined in [src/config/index.ts](mdc:src/config/index.ts): + +- **Gitea Configuration**: + - `GITEA_API_URL`: Gitea API endpoint URL + - `GITEA_ACCESS_TOKEN`: Access token for Gitea API + +- **OpenAI Configuration**: + - `OPENAI_BASE_URL`: OpenAI API base URL + - `OPENAI_API_KEY`: API key for OpenAI + - `OPENAI_MODEL`: Model to use (e.g., "gpt-4o") + +- **Server Configuration**: + - `PORT`: Server port (default: 3000) + - `WEBHOOK_SECRET`: Secret for webhook verification + +- **Custom Prompts**: + - `CUSTOM_SUMMARY_PROMPT`: Custom prompt for summary reviews + - `CUSTOM_LINE_COMMENT_PROMPT`: Custom prompt for line comments + +## Deployment Options + +### Local Development + +```bash +# Development mode with hot reload +bun run dev + +# Production mode +bun run build +bun run start +``` + +### Docker Deployment + +The [Dockerfile](mdc:Dockerfile) provides containerization support: + +```bash +# Build the Docker image +docker build -t gitea-assistant:latest . + +# Run the container +docker run -p 3000:3000 --env-file .env gitea-assistant:latest +``` + +### Kubernetes Deployment + +The [kubernetes.yaml](mdc:kubernetes.yaml) and [kubernetes.yaml.template](mdc:kubernetes.yaml.template) files provide Kubernetes deployment configuration. + +Deployment can be managed using: +```bash +# Apply configuration +kubectl apply -f kubernetes.yaml +``` + +### Webhook Setup + +Configure Gitea webhooks to point to the `/webhook/gitea` endpoint with: +- Content type: application/json +- Secret: matching WEBHOOK_SECRET environment variable +- Events: Pull Request and Status events diff --git a/.cursor/rules/06-contribution-guidelines.mdc b/.cursor/rules/06-contribution-guidelines.mdc new file mode 100644 index 0000000..3c87c6f --- /dev/null +++ b/.cursor/rules/06-contribution-guidelines.mdc @@ -0,0 +1,49 @@ +--- +description: +globs: +alwaysApply: false +--- +# Contribution Guidelines + +## Code Style and Standards + +This project follows TypeScript best practices and uses TSLint for code style enforcement: + +- Configuration: [tslint.json](mdc:tslint.json) +- TypeScript settings: [tsconfig.json](mdc:tsconfig.json) +- Editor config: [.editorconfig](mdc:.editorconfig) + +Run the linter to check code style: +```bash +bun run lint +``` + +## Project Structure Conventions + +When contributing to this project, adhere to these structural guidelines: + +1. **Controller Layer**: + - Business logic should be delegated to services + - Controllers should focus on request handling and response formatting + - Keep route handlers in the [controllers/](mdc:src/controllers) directory + +2. **Service Layer**: + - External API interactions belong in the [services/](mdc:src/services) directory + - Each service should have a clear, single responsibility + +3. **Configuration**: + - Environment-based configurations go in [config/index.ts](mdc:src/config/index.ts) + - Use environment variables for configurable values + +4. **Utils**: + - Reusable utility functions belong in [utils/](mdc:src/utils) + - Logging should use the custom logger from [utils/logger.ts](mdc:src/utils/logger.ts) + +## Pull Request Guidelines + +When submitting Pull Requests: + +1. Include a clear description of changes +2. Ensure code passes linting checks +3. Keep changes focused on a single concern +4. Test your changes locally before submitting diff --git a/.cursor/rules/07-pr-notification.mdc b/.cursor/rules/07-pr-notification.mdc new file mode 100644 index 0000000..92911ac --- /dev/null +++ b/.cursor/rules/07-pr-notification.mdc @@ -0,0 +1,66 @@ +--- +description: +globs: +alwaysApply: false +--- +# PR 通知功能 + +## 概述 + +系统通过飞书(Feishu)实现 PR 相关的通知功能,主要包括 PR 创建通知和审阅者指派通知。核心实现在 [src/services/feishu.ts](mdc:src/services/feishu.ts) 中。 + +## 主要功能 + +### PR 创建通知 + +当 PR 被创建且有指定审阅者时,系统会自动发送通知: +- 触发条件:PR 创建事件 + 存在指定审阅者 +- 通知对象:所有指定的审阅者 +- 通知内容:PR 标题和链接 +- 实现位置:[src/controllers/review.ts](mdc:src/controllers/review.ts) 中的 `handlePullRequestEvent` 函数 + +### 审阅者指派通知 + +当新的审阅者被指派到 PR 时,系统会发送通知: +- 触发条件:PR review_requested 事件 +- 通知对象:新指派的审阅者 +- 通知内容:PR 标题和链接 +- 实现位置:同样在 `handlePullRequestEvent` 函数中 + +## 配置要求 + +使用通知功能需要配置以下环境变量: + +1. **必需配置** + - `FEISHU_WEBHOOK_URL`:飞书 Webhook 地址 + +2. **可选配置** + - `FEISHU_WEBHOOK_SECRET`:飞书 Webhook 密钥(可选,用于加强安全性) + +## 实现细节 + +1. **通知处理流程** + - Webhook 事件由 [src/controllers/review.ts](mdc:src/controllers/review.ts) 接收和处理 + - 通知发送由 [src/services/feishu.ts](mdc:src/services/feishu.ts) 实现 + - 使用飞书的消息 API 发送通知 + +2. **错误处理** + - 通知发送失败不会影响代码审查流程 + - 所有错误都会被记录但不会中断主流程 + - 支持失败重试机制 + +3. **通知格式** + - PR 创建通知:使用 🔄 表情符号 + - 审阅者指派通知:使用 👀 表情符号 + - 包含 PR 标题和可点击的链接 + +## 最佳实践 + +1. **配置建议** + - 建议配置 `FEISHU_WEBHOOK_SECRET` 以增强安全性 + - 确保飞书机器人有足够的权限发送消息 + +2. **使用注意** + - 避免过于频繁的通知以防打扰 + - 确保 PR 标题清晰以便接收者快速理解 + - 合理使用审阅者指派功能,避免过多人员参与 diff --git a/README.md b/README.md index 49d6927..482bbdf 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Gitea Assistant -Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码审查等增强功能。 +Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码审查等增强功能。本工具通过Webhook与Gitea集成,自动对Pull Request和提交进行代码审查,并提供智能化的代码质量分析。 ## 功能特点 @@ -10,6 +10,62 @@ Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码 - ✅ 提供总体代码审查评论 - ✅ 支持代码行级别评论 - ✅ 安全的Webhook验证 +- ✅ 飞书通知集成 +- ✅ 异步处理机制 +- ✅ 智能PR关联分析 +- ✅ 灵活的审查规则配置 + +## 架构设计 + +### 核心组件 + +1. **Webhook处理层** + - 统一的Webhook端点处理 + - 事件类型自动识别 + - 请求签名验证 + - 异步处理机制 + +2. **代码审查引擎** + - 差异分析 + - 文件变更追踪 + - 智能PR关联 + - 审查结果格式化 + +3. **AI集成层** + - OpenAI API集成 + - 可配置的提示模板 + - 结果解析和格式化 + - 错误处理和重试机制 + +4. **通知系统** + - 飞书Webhook集成 + - 多类型通知支持 + - 通知模板配置 + - 失败重试机制 + +### 安全特性 + +- Webhook请求签名验证 +- 环境变量配置管理 +- 敏感信息保护 +- 开发环境安全控制 +- 防时序攻击保护 + +### 性能优化 + +- 异步处理机制 +- 批量处理优化 +- 缓存策略 +- 资源使用监控 +- 错误重试机制 + +### 扩展性 + +- 模块化设计 +- 插件化架构 +- 配置驱动 +- 自定义审查规则 +- 多通知渠道支持 ## 技术栈 @@ -55,6 +111,8 @@ Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码 - `CUSTOM_LINE_COMMENT_PROMPT`: 自定义行评论提示 (可选) - `PORT`: 应用监听端口 (默认: 3000) - `WEBHOOK_SECRET`: Webhook秘钥,用于验证请求来源 +- `FEISHU_WEBHOOK_URL`: 飞书Webhook地址,用于发送通知 +- `FEISHU_WEBHOOK_SECRET`: 飞书Webhook秘钥 (可选) ## 使用方法 @@ -96,6 +154,20 @@ Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码 当PR被创建或更新时,系统会自动进行代码审查,提供总体评价和行级评论。 +### PR通知功能 + +系统支持通过飞书发送PR相关的通知: + +1. **PR创建通知** + - 当PR被创建且有指定审阅者时 + - 通知内容包括PR标题和链接 + - 通知会发送给所有指定的审阅者 + +2. **PR审阅者指派通知** + - 当有新的审阅者被指派到PR时 + - 通知内容包括PR标题和链接 + - 通知会发送给新指派的审阅者 + ### 单个提交审查 当提交状态变为"success"(如CI通过)时,系统会: @@ -106,6 +178,63 @@ Gitea功能增强助手,基于Bun和TypeScript开发,提供AI驱动的代码 这对于增量工作尤其有用,可以只对最新的变更进行审查,避免重复评审已审查过的代码。 +## 代码审查规则 + +### 总体评价规则 + +系统会从以下几个方面对代码进行总体评价: + +1. **代码质量** + - 代码结构是否清晰 + - 命名是否规范 + - 代码是否易于维护 + - 是否有重复代码 + +2. **潜在问题** + - 是否存在明显的逻辑错误 + - 是否有未处理的异常情况 + - 是否有边界条件未考虑 + +3. **性能考虑** + - 是否存在性能瓶颈 + - 是否有不必要的计算或循环 + - 内存使用是否合理 + +4. **安全性** + - 是否有潜在的安全漏洞 + - 敏感信息处理是否安全 + - 输入验证是否充分 + +5. **最佳实践** + - 是否符合语言/框架的最佳实践 + - 是否遵循设计模式 + - 是否有适当的注释和文档 + +### 行级评论规则 + +系统只会在以下情况下对特定代码行提供评论: + +1. **严重问题** + - 明显的bug或逻辑错误 + - 可能导致系统崩溃的代码 + - 严重的安全漏洞 + +2. **性能问题** + - 明显的性能瓶颈 + - 不必要的高复杂度操作 + - 资源使用不当 + +3. **数据一致性问题** + - 可能导致数据不一致的操作 + - 并发访问问题 + - 事务处理不当 + +4. **代码规范问题** + - 严重违反代码规范的情况 + - 可能导致维护困难的结构 + +> 注意:系统默认采用保守策略,不会对没有明显问题的代码行提供评论,以避免产生过多的噪音。 + ## 开发 - `bun run dev`: 开发模式运行 @@ -137,3 +266,111 @@ MIT - ```${file.changes.map(c => `${c.lineNumber}: ${c.content} (${c.type === 'add' ? '新增' : '上下文'})`).join('\n')}``` - 变更行的上下文 请确保你的自定义提示返回正确的格式,特别是对于行评论,必须返回有效的JSON数组。 + +## 部署 + +### Docker部署 + +1. 构建Docker镜像 + + ```bash + docker build -t gitea-assistant . + ``` + +2. 运行容器 + + ```bash + docker run -d \ + --name gitea-assistant \ + -p 3000:3000 \ + --env-file .env \ + gitea-assistant + ``` + +### Kubernetes部署 + +1. 使用提供的kubernetes.yaml模板 + + ```bash + cp kubernetes.yaml.template kubernetes.yaml + ``` + +2. 编辑kubernetes.yaml,更新环境变量和配置 + +3. 部署到Kubernetes集群 + + ```bash + kubectl apply -f kubernetes.yaml + ``` + +## 监控和日志 + +- 应用日志可以通过Docker或Kubernetes的标准日志收集机制获取 +- 建议配置日志聚合服务(如ELK、Grafana Loki等)进行日志管理 +- 关键操作(如代码审查、Webhook处理)都会记录详细日志 +- 错误和异常会被记录并包含堆栈跟踪信息 + +## 故障排除 + +### 常见问题 + +1. **Webhook验证失败** + - 检查`WEBHOOK_SECRET`环境变量是否与Gitea配置匹配 + - 确保请求头中的`X-Gitea-Signature`正确传递 + +2. **OpenAI API调用失败** + - 验证`OPENAI_API_KEY`是否正确设置 + - 检查网络连接和API端点可访问性 + - 确认API配额是否充足 + +3. **Gitea API调用失败** + - 验证`GITEA_ACCESS_TOKEN`是否有效 + - 检查Gitea实例是否可访问 + - 确认令牌权限是否足够 + +### 调试模式 + +在开发环境中,可以设置以下环境变量启用调试模式: + +```bash +DEBUG=true +NODE_ENV=development +``` + +## 贡献指南 + +### 开发流程 + +1. Fork项目并创建特性分支 +2. 提交变更并编写测试 +3. 确保代码通过lint检查 +4. 提交Pull Request + +### 代码规范 + +- 使用TypeScript编写代码 +- 遵循项目中的tslint配置 +- 编写清晰的注释和文档 +- 保持代码风格一致 + +### 测试 + +- 编写单元测试覆盖新功能 +- 确保现有测试通过 +- 测试Webhook处理逻辑 +- 验证AI审查功能 + +## 版本历史 + +- v1.0.0: 初始版本发布 + - 基础代码审查功能 + - Webhook集成 + - OpenAI集成 + - 飞书通知支持 + +## 社区支持 + +- 提交Issue报告问题 +- 参与讨论和功能建议 +- 贡献代码和文档 +- 分享使用经验